Moment JS-解析UTC并转换为Local,反之亦然 [英] Moment JS - parse UTC and convert to Local and vice versa

查看:792
本文介绍了Moment JS-解析UTC并转换为Local,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仔细阅读了文档,对如何进行操作感到有些困惑. 有类似的问题,但是没有人讨论解析格式中收到的特定日期以及在本地日期和utc日期之间交换.

I have gone through the documentation and am a tiny bit confused about how to proceed. There are similar questions, but none talk about parsing particular dates received in formats and swapping between local and utc dates.

  1. 我收到了本地日期时间,本地日期时间格式,并且需要以特定格式从中生成utc日期时间,这就是我认为应该采用的方式. moment(dateTime,localDateTimeFormat).utc().format(specifiedFormat);

我以特定格式接收utc日期时间,并且必须以特定格式生成特定于语言环境的日期时间.我该怎么做? moment.utc(utcDateTime, utcDateTimeFormat).toDate();给了我我相信的JavaScript日期.那我该如何格式化呢?我必须使用生成的Date对象创建新时刻吗?

I receive utc datetime in a particular format and have to generate locale specific datetime in a particular format. How do i do it? moment.utc(utcDateTime, utcDateTimeFormat).toDate(); gives me javascript date i believe. How do I format it then?? Do I have to create a new moment using the generated Date object?

我可以做的另一件事是获取时区,然后进行格式化.我想知道我在这里走的路线是否错误.请帮忙.

Another thing I could do would be getting the timezone and then formatting. I wonder if I am taking the wrong route here. Please help.

推荐答案

  • 关于项目1-是的,这是做到这一点的一种方法.但是,如果输出格式只是ISO8601 UTC时间戳,则可以在原始时刻直接调用toISOString.由于输出暗示了UTC,因此再次调用utc()将是多余的.

    • On Item 1 - Yes, that's one way to do it. However, if the output format is just going to be an ISO8601 UTC timestamp, then you can call toISOString directly on the original moment. Since UTC is implied by the output, it would be redundant to call utc() again.

      关于第2项-与utc()函数一样,还有一个local()函数.一旦有了moment对象,就可以使用toDateformat或文档中描述的任何其他功能.不,您不需要使用生成的日期对象创建新时刻.

      On Item 2 - Just like the utc() function, there's also a local() function. Once you have a moment object, you can use toDate or format or any other of the functions described in the documentation. No, you do not need to create a new moment using the generated date object.

      moment.utc(utcDateTime, utcDateTimeFormat).local().format(specifiedFormat)
      

      同样,在这里做事的方法不止一种.如果utcDateTime已经是ISO8601格式,并且包含Z-01:00之类的偏移量,则将其考虑在内,您可以简单地执行以下操作:

      Again, there's more than one way to do things here. If the utcDateTime is already in ISO8601 format, and contains either a Z or an offset like -01:00, then that will be taken into account and you can simply do this:

      moment(utcDateTime).format(specifiedFormat)
      

    • 在您提到的有关时区的最后一项上,很难说出您要问的问题.您应该在新问题中详细说明.

      这篇关于Moment JS-解析UTC并转换为Local,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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