简体   繁体   English

在javascript(moment.js)中将UTC日期转换为当地时间

[英]convert UTC date to local time in javascript (moment.js)

I receive the following date as JSON data from an ASP.NET webapi2 service. 我从ASP.NET webapi2服务收到以下日期作为JSON数据。

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

The dates in the system are stored as UTC dates, independent of the time zone. 系统中的日期存储为UTC日期,与时区无关。 When the data is returned and displayed on screen the incorrect time is used, as moment assumes that the date being parsed is local time, not UTC. 当返回数据并在屏幕上显示时,会使用不正确的时间,因为时刻假定要解析的日期是本地时间,而不是UTC。

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

Gives me time values two hours in the past, when they should actually be current. 给我两个小时的时间值,当时它们应该是最新的。 How do I parse / pass the date so that moment knows it should add the time zone. 如何解析/传递日期,以便知道它应该添加时区。 In my case GMT+2 or SAST. 在我的情况下GMT + 2或SAST。

Adding the time zone (GMT) doesn't seem to help. 添加时区(GMT)似乎没有帮助。

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

results in NaN 导致NaN

You have at least two options: 您至少有两个选择:

  1. Add a Z to the end of the string: 在字符串的末尾添加Z

     moment(creationDate + "Z") 
  2. Use .utc and then .local : 使用.utc然后.local

     moment.utc(creationDate).local() 

Here's an example, using a date that's almost always in daylight savings time ("summer time") so that it even works for those of us in the UK (who are otherwise on GMT, so it can be hard to tell whether we're getting UTC or local results :-) ): 这是一个例子,使用几乎总是在夏令时(“夏令时”)的日期,这样它甚至适用于我们在英国的人(否则他们在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> 

The issue is when you send/receive the date both client and server will try to convert to their time zone, the trick is that, pass the date as string. 问题是当您发送/接收客户端和服务器将尝试转换为其时区的日期时,诀窍是,将日期作为字符串传递。 When you returning or sending the data remove the "T" 当您返回或发送数据时删除“T”

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

OR 要么

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

So when client receive the data it will not change or convert the date. 因此,当客户端收到数据时,它不会更改或转换日期。 then you can use 然后你可以使用

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

This will return what you have sent from server 这将返回您从服务器发送的内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM