Reputation: 369
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
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:
moment(String)
moment(String, String)
passing moment.ISO_8601
as format parametertoJSON()
output ('YYYY-MM-DDTHH:mm:ss.SSSZ'
)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