moment.js not properly converting epoch to ISO8601

I am using moment.js to convert time in ISO8601 format to epoch. However when I convert back the result is not the same. Any ideas?

node.js code

var moment = require('moment');
var input ="2014-08-23T15:05:36-07:00";
var a = moment(input,moment.ISO_8601).valueOf();
console.log ("convert ISO8601 to epoch time:" + input + "====>" + a);
var b = moment(parseInt(a)).format("YYYY-MM-DDTHH:MM:SSZ");
console.log ("convert epoch time to ISO8601:" + a + "====>" + b);

output

convert ISO8601 to epoch time:2014-08-23T15:05:36-07:00====>1408831536000
convert epoch time to ISO8601:1408831536000====>2014-08-23T15:08:00-07:00

I always use moment.format() to get an ISO8601 string instead of passing in a custom format string. Example:

var moment = require('moment');
var input ="2014-08-23T15:05:36-04:00";
var a = moment(input,moment.ISO_8601).valueOf();
console.log ("convert ISO8601 to epoch time:" + input + "====>" + a);
var b = moment(parseInt(a)).format();
console.log ("convert epoch time to ISO8601:" + a + "====>" + b);

outputs:

convert ISO8601 to epoch time:2014-08-23T15:05:36-04:00====>1408820736000
convert epoch time to ISO8601:1408820736000====>2014-08-23T15:05:36-04:00

A few things:

  • You used a format string of "YYYY-MM-DDTHH:MM:SSZ". However MM refers to months, not minutes - and SS is for the first two decimal places of fractional seconds. If you wanted to provide a format string, it would be "YYYY-MM-DDTHH:mm:ssZ". It is case sensitive.

  • As mscdex pointed out, you could just use .format() without any parameters, as this is the default output format.

  • moment.ISO_8601 is not necessary in this case, as you are only parsing a single format and ISO-8601 is understood by default.

  • parseInt is also not required. Moment will understand the value passed in as an integer or a string.

As such, the code can be reduced to:

var moment = require('moment');
var input ="2014-08-23T15:05:36-04:00";
var a = moment(input).valueOf();
console.log ("convert ISO8601 to epoch time:" + input + "====>" + a);
var b = moment(a).format();
console.log ("convert epoch time to ISO8601:" + a + "====>" + b);