简体   繁体   English

为什么Moment.JS无法正确解析24小时日期

[英]Why does Moment.JS not parse 24 hour dates correctly

Whenever I parse dates using moment.js & node, it is exactly 12 hours out from what it should be. 每当我使用moment.js和node解析日期时,它应该是12个小时。 Consider the following test: 考虑以下测试:

var moment = require('moment');

var dt1 = moment('14:00, 10 Jun 2014', 'HH:mm, DD MMM YYYY').toDate();
console.log('dt1:' + JSON.stringify(dt1, null, 4));

var dt2 = moment('02:00, 10 Jun 2014', 'HH:mm, DD MMM YYYY').toDate();
console.log('dt2:' + JSON.stringify(dt2, null, 4));

It gives the output: 它给出了输出:

dt1:"2014-06-10T02:00:00.000Z"
dt2:"2014-06-09T14:00:00.000Z"

Its almost like its parsing it using some crazy timezone and not just parsing the date in my local timezone as I want, which I would have thought would be be the default behaviour. 它几乎就像使用一些疯狂的时区解析它而不只是按照我想要的方式解析当地时区的日期,我原本认为这将是默认行为。

How can I make it work properly? 我怎样才能让它正常工作?

尝试以下内容

var dt1 = moment('14:00, 10 Jun 2014', 'HH:mm, DD MMM YYYY').format('HH:mm, DD MMM YYYY');

Moment.js is working correctly. Moment.js工作正常。 Source of your problem is JSON.stringify that converts date to UTC. 您的问题的来源是JSON.stringify,它将日期转换为UTC。 So you need to add your timezone to timestamp to fix that. 因此,您需要将时区添加到时间戳以修复该问题。 And simplest way to do that is to warp your first moment object to second one for changing of format and set default format using format call without parameters (look for Default format here). 最简单的方法是将您的第一个时刻对象转换为第二个对象以更改格式,并使用不带参数的格式调用设置默认格式(在此处查找默认格式)。

moment(moment('02:00, 10 Jun 2014', 'HH:mm, DD MMM YYYY').toDate()).format();

Update: 更新:

It's more simple as @MattJohnson figure out. 正如@MattJohnson所说,它更简单。 Not sure why it's not worked before for me, but it's just need to be: 不知道为什么它以前不适用于我,但它只需要:

moment('02:00, 10 Jun 2014', 'HH:mm, DD MMM YYYY').format()

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

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