【问题标题】:Using UTC dates between .NET and JavaScript在 .NET 和 JavaScript 之间使用 UTC 日期
【发布时间】:2012-04-23 15:43:38
【问题描述】:

我正在使用ASP.NET MVC,我希望将我所有的 DateTime 值以 UTC 格式存储在服务器上。我希望 DateTime 值的所有传输都采用 UTC 格式。但我想在本地时间在浏览器中显示 DateTimes。我一直感到困惑并且无法使其正常工作。下面是我的过程......

在我的 UI 中,用户可以输入一个日期,我将其组合成一个字符串并用于创建一个 Date 对象。它最终看起来像这样:

var dt = new Date("3/23/2012 8:00 AM");

因此,用户打算为他们的时间上午 8 点创建一个日期。现在我希望以 UTC 格式将其发送到服务器,所以我有这个方法:

Date.prototype.toUTC = function ()
{
    var self = this;
    return new Date(self.getUTCFullYear(), self.getUTCMonth(), self.getUTCDate(), self.getUTCHours(), self.getUTCMinutes());
};

我是这样使用的:

data.startDt = dt.toUTC();  //Data is the object being set to the server

然后我使用 jQuery 进行 Ajax 调用以将数据对象发送到服务器。在服务器上,当我调试并检查传入的数据时,我看到 StartDt(映射到 .NET DateTime 对象)为 {3/23/2012 12:00:00 PM}。

这是我存储在数据库中的值。不过我并不完全确定它是否正确。

客户端和服务器都位于美国东部 (UTC-05:00)。

现在,当我以 JSON 格式将此日期发送回客户端时,.NET 会发送以下内容:

"/Date(1332518400000)/"

在 JavaScript 中我是这样解析的:

var dt = new Date(parseInt(serverDt.substr(6)));    //parseInt ingnores last /

我的想法是 dt 是一个 UTC 日期,但我可以通过调用 toShortTime() 以本地格式显示它,如下所示:

Date.prototype.get12Hour = function ()
{
    var h = this.getHours();
    if (h > 12) { h -= 12; }
    if (h == 0) { h = 12; }
    return h;
};

Date.prototype.getAMPM = function ()
{
    return (this.getHours() < 12) ? "AM" : "PM";
};

Date.prototype.toShortTime = function ()
{
    return this.get12Hour() + ":" + this.getMinutes() + " " + this.getAMPM();
};

但这并没有给我想要的 8:00 AM 返回。它给了我 12:00 PM。我哪里错了?

【问题讨论】:

  • 在您的代码中,dt 是 UTC 时间。您需要将其从 UTC 转换为本地时间。见stackoverflow.com/questions/3741348/…
  • 我认为您可能是正确的。如果我运行这个new Date(Date.UTC(dt.getFullYear(), dt.getMonth(), dt.getDate(), dt.getHours(), dt.getMinutes()));,我会回到早上 8 点。
  • 如果你把它写成答案,我会给你功劳。

标签: javascript asp.net-mvc json


【解决方案1】:

在您的代码中,dt 是 UTC 时间。您需要将其从 UTC 转换为本地时间。
Javascript: Convert a UTC Date() object to the local timezone

【讨论】:

    【解决方案2】:

    您是否正在使用适当的 DateTimeKind 值构造 .NET DateTime 对象?您正在向服务器发送一个 UTC 相对值,我猜这是将该值存储为 EDT 相对时间而不是 UTC 相对时间,因此值不正确。正如您所说,1332518400000 是美国东部时间下午 12 点,而不是 UTC,这表明服务器上存在转录问题:

    > new Date(1332518400000)
    Fri Mar 23 2012 12:00:00 GMT-0400 (Eastern Daylight Time)
    

    【讨论】:

    • 好吧,数据被传递给一个MVC控制器,ModelBinder实际上是在创建DateTime对象。这是客户端发送的内容:2012-03-23T16:00:00.000Z
    • 我不得不承认,我很困惑 8:AM 是如何在 16:00 发送的,但我确实认为最后的 Z 表示 UTC。
    【解决方案3】:

    这个功能非常适合我。

    function ParseDateForSave(dateValue) {
        // create a new date object
        var newDate = new Date(parseInt(dateValue.substr(6)));
    
        // return the UTC version of the date
        return newDate.toISOString();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-19
      • 2014-12-17
      • 2012-01-30
      • 2014-06-13
      • 2021-05-14
      • 2023-03-21
      • 2012-04-18
      • 1970-01-01
      相关资源
      最近更新 更多