10

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?

5
  • You'd think this use case would be covered by Moment Timezone, but it sure doesn't look like it from the docs. Not very impressive. Commented Feb 1, 2017 at 16:33
  • x.format() gives me (moment 2.17.1, tz Europe/Rome) Invalid date and Deprecation warning. I fear that the problem is +6:00 instead of +06:00 (2 digit) for offset in your input string
    – VincenzoC
    Commented Feb 1, 2017 at 16:44
  • Gives invalid date on momentjs website. Can you confirm once ? Commented Feb 1, 2017 at 16:49
  • Just get a result as close as possible and fix it yourself later with string manipulation and a little bit of regex. Commented Feb 1, 2017 at 16:50
  • 2
    @Nonemoticoner - that's ridiculous. Commented Feb 1, 2017 at 20:32

1 Answer 1

8

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"
    

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.