Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moment.js issues with .format() using Zulu time

I am working on a script that needs to retrieve and store a timestamp from a database. The timestamp from the database is retrieved as a UTC Zulu formatted string "YYYY-MM-DDTHH:MM:SS.SSSZ". I want to store this timestamp in the format "YYYY-MM-DDTHH:MM:SS.SSS" in local time. I am currently attempting to do this with moment.js, I have had little success with ".toISOString()" and other methods.

However, I have noticed that the output from "moment(timestamp).format()" does not return the string I am expecting from what I understand so far about UTC. Here is a code example that replicates my issue:

var moment = require('moment');

var timestamp = new Date('2018-05-30T15:01:01.111Z');

console.log(timestamp);
console.log(moment(timestamp).format('YYYY-MM-DDTHH:mm:ss.sss'));
console.log(moment(timestamp).format('YYYY-MM-DDTHH:MM:SS.SSS'));

This is my output:

2018-05-30T15:01:01.111Z
2018-05-30T16:01:01.011
2018-05-30T16:05:11.111

This is my expected out:

2018-05-30T15:01:01.111Z
2018-05-30T16:01:01.111
2018-05-30T16:01:01.111

Why does the change in case from 'YYYY-MM-DDTHH:mm:ss.sss' to 'YYYY-MM-DDTHH:MM:SS.SSS' in .format() cause a different output? Is my expected output correct or have a misunderstood moment.(timestamp).format()? Lastly, is there a better way to achieve my expected output given the circumstances?

like image 330
Todd Avatar asked Jan 29 '23 00:01

Todd


1 Answers

http://momentjs.com/docs/#/displaying/format/

MM is months thats why you got 2018-05-30T16:05:11.111 a 5

there is no sss but there is a SSS

you said you want in this format "YYY-MM-DDTHH:MM:SS.SSS" I assume MM you mean minutes due to your expected outcome. This is an odd way to store a date as there are no months and it's repeating seconds.

I'd suggest storing in UTC.

var timestamp = new Date('2018-05-30T15:01:01.111Z');

console.log(timestamp);
console.log(moment(timestamp).format('YYYY-MM-DDTHH:mm:ss:SSS'));

// i'd suggest UTC over formating but if you were i'd use
console.log(moment(timestamp).format('YYYY-MM-DDTHH:MM:mm:SSS'));
//2018-05-30T15:01:01.111Z
//2018-05-30T16:01:01.111
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.js"></script>

Please let me know if this how you want it.

like image 79
Joe Warner Avatar answered Jan 31 '23 08:01

Joe Warner