简体   繁体   中英

How to get Date String Format in JavaScript using moment or vanilla JavaScript?

So I have this sample date "2015-11-13T18:43:58.720Z" and I want to get the string format of it. I used moment to get the string format.

const d = '2015-11-13T18:43:58.720Z';
const format = moment(d).creationData().format;
// output is YYYY-MM-DDTHH:mm:ss.SSSSZ

But when I do something like

const a = moment(d).format('MM-DD-YYYY HH:mmA');
// output is 11-14-2015 02:43AM

const b = moment('11-14-2015 02:43AM', 'MM-DD-YYYY HH:mmA').format('YYYY-MM-DDTHH:mm:ss.SSSSZ');
// output is different 2015-11-14T02:43:00.0000+08:00
// expecting 2015-11-13T18:43:58.720Z

How can I get the proper string format of (2015-11-13T18:43:58.720Z) using moment or vanilla js when getting current timestamp?

You can do that in Vanilla JavaScript, without moment.js.

const newDate = new Date().toISOString();
console.log(newDate)

This converts the input into the date in ISO format (as a string).

More examples:

  const newDate = new Date().toISOString(); const anotherDate = new Date('2015-11-13T18:43:58.720Z').toISOString(); const yetAnotherDate = new Date(2019, 3, 15, 10).toISOString(); console.log(newDate); console.log(anotherDate); console.log(yetAnotherDate); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM