js返回iso时间戳的格式错误的值的那一刻 [英] moment js is returning wrong formatted values for an iso timestamp

查看:82
本文介绍了js返回iso时间戳的格式错误的值的那一刻的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将此时间戳"2018-01-31T22:55:02.907Z"传递给moment()函数,但是在格式化日期部分后返回错误的值.

I'm passing "2018-01-31T22:55:02.907Z" this timestamp to the moment() function but it returns the wrong value after formatting the date part.

console.log(moment("2018-01-31T22:55:02.907Z").format('YYYY-MM-DD'));

这应该返回2018-01-31,而是返回2018-02-01.

This should return 2018-01-31 but rather it's returning 2018-02-01.

像这样,每个日期都增加了一天.我怀疑是基于时区的问题,但无法解决.

It's adding one day to every date like that. I'm suspecting some time zone based issue but I'm not able to figure it out.

推荐答案

传递时间戳时必须使用.utc,如下所示: 如果您这样做:

You have to use .utc when passing timestamp like this: If you do:

console.log(moment("2018-01-31").format('YYYY-MM-DD'));

它会给您想要的结果,但是当像现在一样传递时间戳时,您应该做的是:

It would give you the desired result but when passing timestamp like you have done now, what you should do is:

console.log(moment.utc("2018-01-31T22:55:02.907Z").format('YYYY-MM-DD'));

您还可以查看其工作原理:

You can also see how this works:

console.log(moment({ years:2018, months:0, date:31, hours:22, minutes:55, seconds:02, milliseconds:907}).format('YYYY-MM-DD'));

要传递时间戳,您应该再次检查文档. https://momentjs.com/docs/#/parsing/unix-timestamp -毫秒/

For passing timestamp you should check the documentation again. https://momentjs.com/docs/#/parsing/unix-timestamp-milliseconds/

这可能也是一个有用的链接: https://coderwall.com/p/exrbag/use- momentjs-to-parse-unix-timestamps

This also might be a helpful link: https://coderwall.com/p/exrbag/use-momentjs-to-parse-unix-timestamps

这篇关于js返回iso时间戳的格式错误的值的那一刻的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆