将 UTC DateTime 从服务器转换为网页上的本地 DateTime

Convert UTC DateTime from server to Local DateTime on web page

我在 Sql 中有一个 DateTime 列字段,它将值存储为 UTC。现在我有一个要求,在我的报告中,我必须根据用户访问报告的地理位置将 UTC 转换为 Local Time

现在我知道 ToLocalTime() 会将其转换为必需的,但同时它将转换为部署应用程序的位置,即服务器而不是用户的地理位置。

这是我的代码片段..

<td>@string.Format("{0:yyyy-MMM-dd HH:mm:ss}", user.StatusDateTime.ToLocalTime())</td>

我在用户界面中使用 Razor 视图和 javascript/jquery
可能的解决方案是什么?

好的,你可以做的是,将日期传递给视图(没有 .ToLocalTime()),然后使用 JavaScript 呈现本地日期,如 link 所示。

<script>document.write(new Date('@user.StatusDateTime.ToString("yyyy-MM-dd hh:mm:ss UTC")').toString());</script>

注意.ToString("yyyy-MM-dd hh:mm:ss UTC")满足JavaScript(我想还有更好的方法)。

编辑

如果您想以某种特定格式显示日期(例如 2015-Dec-22 12:11:38),您可以使用自定义 JavaScript功能。这是一个例子。

function getFormattedLocalDate(utcDateString) {
    var date = new Date(utcDateString);
    var months = [
      "Jan", "Feb", "Mar", "Apr", "May", "Jun", 
      "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
    ];
    var formattedDate = date.getFullYear() + '-' + months[date.getMonth()] + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
    return formattedDate;
}

看到了live.

编辑 2

内部示例使用 html table here.