[英]How do I prevent javascript from converting my dates to GMT?
I have a timestamp given by 我有一个时间戳
timestamp = 2015-02-22T10:00:00.000Z
Why is it converted to GMT when I do this 为什么我这样做时会转换为GMT
var dt = new Date(timestamp);
console.log('dt = ' + dt); // prints Sun Feb 22 2015 05:00:00 GMT-0500 (EST)
I don't want it to convert my date to GMT. 我不希望它将我的约会转换为GMT。 How do I prevent javascript from converting my dates? 如何防止javascript转换我的日期?
When you try to execute dt = ' + dt
, Javascript tries to convert the dt
object to a string so it can be added to another string. 当您尝试执行dt = ' + dt
,Javascript会尝试将dt
对象转换为字符串,以便将其添加到另一个字符串中。 It does that by calling the dt.toString()
method and the format you are seeing is the default string conversion for a date object. 它通过调用dt.toString()
方法来实现,您看到的格式是日期对象的默认字符串转换。
FYI, this default format that looks like this: 仅供参考,此默认格式如下所示:
Fri Mar 06 2015 19:24:42 GMT-0800 (Pacific Standard Time)
is NOT GMT time. 不是格林尼治标准时间。 The time value shown is local time. 显示的时间值是当地时间。 It is showing you that local time shown is -0800 hours from GMT, but the time itself is expressed in local time. 它显示当地时间显示距格林威治标准时间-0800小时,但时间本身以当地时间表示。
It's not uncommon to want to just truncate off the last part of this and display: 想要截断它的最后一部分并显示它并不罕见:
Fri Mar 06 2015 19:24:42
That can be done like this: 这可以这样做:
console.log('dt = ' + dt.toString().replace(/\sGMT.*$/, ""));
Working demo: http://jsfiddle.net/jfriend00/hg5m0r1r/ 工作演示: http : //jsfiddle.net/jfriend00/hg5m0r1r/
If you want something different to show, then you should construct the string representation you want yourself rather than letting the system automatically call .toString()
. 如果你想要显示不同的东西,那么你应该构建你想要的字符串表示,而不是让系统自动调用.toString()
。 You can look at the Date object methods available and decide what you want to display. 您可以查看可用的Date对象方法并确定要显示的内容。 A Date object internally is a number of ms since the epoch time so any string representation is a conversion of some kind. 内部的Date对象是纪元时间以来的ms数,因此任何字符串表示都是某种转换。 You have to tell it what conversion you want. 你必须告诉它你想要的转换。
You can see a list of the many date methods here . 您可以在此处查看许多日期方法的列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.