Search code examples
node.jsdatetimezonemomentjsmoment-timezone

how do I maintain time offsets in moment?


I'm trying to add/subtract days from moment time object. However, the problem im having is that the time offset is different then the local time of the server.

in db my time

2019-08-14T21:38:50-04:00

however, locally I get +0000

moment().format('YYYY-MM-DD hh:mm ZZ')
2019-08-15 07:19 +0000

so now if I try to convert the time stored in the db

moment("2019-08-14T21:38:50-04:00").format('YYYY-MM-DD hh:mm ZZ')
2019-08-15 01:38 +0000

if I use parseZone() I get

moment.parseZone("2019-08-14T21:38:50-04:00").format('YYYY-MM-DD hh:mm ZZ')
2019-08-14 09:38 -0400

I also tried manually removing the offset of 4 hours (to balance it out?)

moment("2019-08-14T21:38:50-04:00").utcOffset(-240).format('YYYY-MM-DD hh:mm ZZ')
2019-08-14 09:38 -0400

But the value out (after formatting) is always different then in.

How do I get 2019-08-14T21:38:50-04:00 as the output after I format moment obj back to a string?


Solution

  • moment.parseZone("2019-08-14T21:38:50-04:00").format()
    

    or

    moment.parseZone("2019-08-14T21:38:50-04:00").format(moment.ISO_8601())
    

    or

    moment.parseZone("2019-08-14T21:38:50-04:00").format("YYYY-MM-DD[T]HH:mm:ssZ")
    

    All of the above will produce "2019-08-14T21:38:50-04:00", the same as the input string.

    The main problem in your third attempt is that you were using hh (12-hour clock) instead of HH (24-hour clock).