Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Momentjs format moment object and keep offset

I have a momentjs object that hold a datetime with an offset. This moment object was created from its string representation:

var x = moment("2017-02-08T04:11:52+6:00")

After working with the object, I would like to get the same textual representation from the moment object.

I get the following results when trying to format the object:

  • x.format() => "2017-02-08T04:11:52+14:00"
  • moment.parseZone(x).format("YYYY-MM-DDTHH:mm:ssZ") => "2017-02-07T14:11:52+00:00"

How can I format my moment object such that I have the exact same representation again?

like image 318
JasperTack Avatar asked Feb 01 '17 16:02

JasperTack


1 Answers

A few things:

  • Your input is nonstandard because you've specified the offset as +6:00. The ISO8601 format requires two digits in both hours and minutes offset. (It shouold be +06:00. For the rest of this answer, I'll assume that's a typo.)

  • You're losing the original offset when you create the moment, because you are adjusting to the local time zone by calling moment(...). Therefore it doesn't exist in x, at least not in a way you can retrieve it.

  • In general, parseZone should be passed a string, not a Moment object.

  • You certainly can format as you asked, as long as you have parsed correctly to begin with. You don't even need to specify a format string, as the one you're looking for is the default.

    var str1 = "2017-02-08T04:11:52+06:00";
    var mom = moment.parseZone(str1);
    var str2 = mom.format();  // "2017-02-08T04:11:52+06:00"
    
like image 165
Matt Johnson-Pint Avatar answered Nov 14 '22 10:11

Matt Johnson-Pint