ASP.NET MVC控制器/视图显示本地时间

Mat*_*ttW 13 javascript asp.net-mvc timezone datetime

我有一个ASP.NET MVC应用程序,它以UTC格式存储所有SQL DateTime,因此无论客户端从哪个时区访问该站点,时间都是一致的.

现在,我想重新向用户显示正确的时间,所以每次在我的View中显示时间我都会使用:

timeVariable.ToLocalTime();
Run Code Online (Sandbox Code Playgroud)

但是,.ToLocalTime()基于服务器,而不是客户端.

我是否需要在客户端上使用JavaScript处理此问题?

我可能可以将时区作为请求的一部分传递并让控制器处理该事件,但我假设有更好的方法来执行此操作.或者不存在?

在此先感谢您的帮助!

-Matt

Der*_*ick 12

对于Asp.Net MVC + jQuery,我创建了一个DisplayTemplate和脚本来帮助解决这个问题.

型号类:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

public class SampleModelWithDate
{
    [UIHint("UTCTime")]
    [DataType(DataType.DateTime)]
    public DateTime Date { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

DisplayTemplate:Views\Shared\DisplayTemplates\UTCTime.cshtml

@model DateTime
<span class="UTCTime">@Model</span>
Run Code Online (Sandbox Code Playgroud)

添加到Views\Shared_Layout.cshtml,或添加到您的视图:

<script>
    $(function () {
        // Determine timezone offset in milliseconds
        // from: http://www.w3schools.com/jsref/jsref_getTimezoneOffset.asp
        var d = new Date()
        var offsetms = d.getTimezoneOffset() * 60 * 1000;
        $('.UTCTime').each(function () {
            try
            {
                var text = $(this).html();

                var n = new Date(text);
                n = new Date(n.valueOf() - offsetms);

                $(this).html(n.toDateString() + " " + n.toLocaleTimeString());

                $(this).attr("Converted from UTC " + text);
            }
            catch (ex) {
                console.warn("Error converting time", ex);
            }
        });
    });
</script>
Run Code Online (Sandbox Code Playgroud)

当然要清理一下,它有点冗长,所以你可以看到发生了什么.

  • 感谢您的详细回答。 (3认同)

Mik*_*all 5

几乎所有我见过的将时间转换为当地时间的网站都要求用户在创建帐户时指定他或她的时区.Gmail就是一个例子,但还有很多其他例子.

我发现很多尝试在IP地址上使用javascript或反向查找的解决方案都容易出现故障和边缘情况.