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?
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With