agnor
agnor

Reputation: 369

Momentjs strict format always returns 'Invalid date'

According to momentjs docs toJSON() produces ISO 8601 formatted string and moment.defaultFormat is ISO 8601 format.

Taking this in account I would expect to get a valid date, but

moment(moment().toJSON(), moment.defaultFormat, true).toString() 

always returns 'Invalid Date'.

Upvotes: 3

Views: 956

Answers (1)

VincenzoC
VincenzoC

Reputation: 31482

You are right, moment().toJSON() returns an ISO 8601 format, but is not the same of moment.defaultFormat.

The issue is that moment().toJSON() includes fractional seconds (SSS token) that are not part of moment.defaultFormat (that is YYYY-MM-DDTHH:mm:ssZ).

moment().toJSON() output can be parsed:

Here a live sample:

console.log( moment(moment().toJSON(), moment.defaultFormat, true).toString()  );

console.log( moment().toJSON() );
console.log( moment.defaultFormat );

console.log( moment(moment().toJSON(), 'YYYY-MM-DDTHH:mm:ss.SSSZ', true).toString()  );

console.log( moment(moment().toJSON(), moment.ISO_8601, true).toString()  );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

Upvotes: 5

Related Questions