Moment JS - parse UTC and convert to Local and vic

2019-01-17 03:09发布

问题:

This question already has an answer here:

  • moment.js - UTC does not work as i expect it 2 answers

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. I receive a local datetime, local datetime format and need to generate utc datetime from it in a particular format and this is how I think I should do it. moment(dateTime,localDateTimeFormat).utc().format(specifiedFormat);

  2. 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:

  • 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.

  • 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)
    

    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)
    
  • On the last item you mentioned about time zones, it's difficult to tell what you are asking. You should elaborate with specific details in a new question.



标签: momentjs