转换JSON日期没有时区 [英] Convert JSON dates without timezone
问题描述
我有,例如返回一个DateTime对象一个Web服务:DepartureDate。
我使用Ajax来获取这一点,在我看来,我的JSON日期字符串转换为JavaScript日期对象来使用此功能:
函数convertToDate(jsonDate){
返回的eval(新+ jsonDate.substring(1,jsonDate.length - 1));
}
问题是,新的Date()
需要考虑客户端计算机上的本地时间,所以在不同国家的客户得到不同的日期。我想这是从Web服务返回的确切日期。
有没有简单的方法来做到这一点?
问题是,
新的Date()
需要当地时间客户端计算机上的考虑。
块引用>不。创建使用时间戳构造一个新的Date需要UTC时间戳记。
例如我在UTC + 1台机器上:
新的日期(0)//周四1970年1月1日01:00:00 GMT + 0100(CET)
OK,默认
的toString
的显示的这个日期作为一时00分00秒这看起来的错,但那是其实正确的时间。 1时00分00秒在UTC + 1是UTC,它是由时间戳所描述的那一刻0时00分00秒0
。如果你想显示你从UTC时间戳创建日期,使用
date.toUTCString()
或获取和使用格式化日期的consistuent部分调用getUTCFullYear()
,getUTCMonth()
等。请,虽然没有
评估
。新的日期(parseInt函数(jsonDate.slice(6 -1),10))
I have a webservice that returns for example a DateTime object: DepartureDate. I use ajax to fetch this and in my view I convert the JSON date string to a javascript date object with this function:
function convertToDate(jsonDate) { return eval("new " + jsonDate.substring(1, jsonDate.length - 1)); }
The problem is that
new Date()
takes the local time on the clients computer in consideration, so clients in different countries get different dates. I want to get the exact date that was returned from the webservice. Is there any easy way to accomplish this?解决方案The problem is that
new Date()
takes the local time on the clients computer in considerationNope. Creating a new Date using the timestamp constructor takes a UTC time stamp.
For example on my machine in UTC+1:
new Date(0) // Thu Jan 01 1970 01:00:00 GMT+0100 (CET)
OK, the default
toString
displays this date as 01:00:00 which looks wrong, but that's actually the correct time. 01:00:00 in UTC+1 is 00:00:00 in UTC, which is the moment described by timestamp0
.If you want to display the dates you've creating from a timestamp in UTC, use
date.toUTCString()
or fetch and format the consistuent parts of the date usinggetUTCFullYear()
,getUTCMonth()
etc.Please, though, no
eval
.new Date(parseInt(jsonDate.slice(6, -1), 10))
这篇关于转换JSON日期没有时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!