Salar
Salar

Reputation: 5509

moment.js format date in TZ format

I want to cast MySql datetime strings like

2018-05-17 15:03:31

to format like :

2018-05-17T15:03:31.000Z

How can I do that using moment.js library?

Upvotes: 2

Views: 838

Answers (1)

VincenzoC
VincenzoC

Reputation: 31482

Since you input is in ISO 8601 format, you can parse it using moment.utc (see Local vs UTC vs Offset), then you can simply use toISOString():

Note that .toISOString() returns a timestamp in UTC, even if the moment in question is in local mode. This is done to provide consistency with the specification for native JavaScript Date .toISOString(), as outlined in the ES2015 specification. From version 2.20.0, you may call .toISOString(true) to prevent UTC conversion.

var input = '2018-05-17 15:03:31';
console.log( moment.utc(input).toISOString() );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>

Upvotes: 2

Related Questions