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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With