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?
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?
Share Improve this question edited Feb 1, 2017 at 16:46 VincenzoC 31.5k12 gold badges100 silver badges121 bronze badges asked Feb 1, 2017 at 16:26 JasperTackJasperTack 4,4575 gold badges30 silver badges43 bronze badges 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. – T.J. Crowder Commented Feb 1, 2017 at 16:33
-
x.format()
gives me (moment2.17.1
, tzEurope/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 ? – kawadhiya21 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. – Nonemoticoner Commented Feb 1, 2017 at 16:50
- 2 @Nonemoticoner - that's ridiculous. – Matt Johnson-Pint Commented Feb 1, 2017 at 20:32
1 Answer
Reset to default 8A 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 inx
, at least not in a way you can retrieve it.In general,
parseZone
should be passed a string, not aMoment
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"