【问题标题】:convert UTC date to local time in javascript (moment.js)在javascript(moment.js)中将UTC日期转换为本地时间
【发布时间】:2017-04-15 09:29:08
【问题描述】:

我从 ASP.NET webapi2 服务收到以下日期作为 JSON 数据。

{
    creationDate: "2014-11-18T15:16:56.363"
    ... //other fields...
}

系统中的日期存储为 UTC 日期,与时区无关。 当数据返回并显示在屏幕上时,使用了不正确的时间,因为 moment 假定正在解析的日期是本地时间,而不是 UTC。

moment(text).tz('Africa/Johannesburg').fromNow();

给我两个小时前的时间值,此时它们实际上应该是当前的。我如何解析/传递日期,以便知道它应该添加时区。在我的情况下,GMT+2 或 SAST。

添加时区 (GMT) 似乎没有帮助。

Date.parse('2017-04-15T09:09:48.9590011 UTC')

结果为@​​987654325@

【问题讨论】:

  • 来自official documentation“如果要解析或显示UTC的时刻,可以使用moment.utc()而不是moment()。”

标签: javascript asp.net-mvc asp.net-web-api2 momentjs


【解决方案1】:

您至少有两个选择:

  1. 在字符串末尾添加Z

    moment(creationDate + "Z")
    
  2. 使用.utc,然后使用.local

    moment.utc(creationDate).local()
    

这是一个示例,使用的日期几乎总是夏令时(“夏令时”),因此它甚至适用于我们这些在英国的人(否则他们在 GMT,因此很难判断是否我们得到 UTC 或本地结果 :-) ):

var creationDate = "2014-05-18T15:16:56.363";
console.log("String:", creationDate);
console.log("1:", moment(creationDate + "Z").toString());
console.log("2:", moment.utc(creationDate).local().toString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

【讨论】:

    【解决方案2】:

    问题是当您发送/接收日期时,客户端和服务器都将尝试转换为他们的时区,诀窍是,将日期作为字符串传递。 当您返回或发送数据时,删除 "T"

    {
        creationDate: "2014-11-18 15:16:56.363"
        ... //other fields...
    }
    

    data.creationDate.replace('T', ' ')
    

    因此,当客户端收到数据时,它不会更改或转换日期。那么你可以使用

    new Date(moment(data.creationDate.replace('T', ' ')))
    

    这将返回您从服务器发送的内容

    【讨论】:

      猜你喜欢
      • 2014-07-23
      • 2021-03-26
      • 1970-01-01
      • 2012-10-07
      • 1970-01-01
      • 1970-01-01
      • 2019-06-21
      • 1970-01-01
      • 2021-10-17
      相关资源
      最近更新 更多