简体   繁体   中英

Get date time in specific format in moment js

I am trying to get the date time in moment js in this format :

2016-12-19T09:43:45.672Z

The problem is I am able to get the time format as

2016-12-19T15:04:09+05:30

using

moment().format();

but I need the format as the first one [like .672Z instead of +05:30]. Any suggestions would be of great help.

From the documentation on the format method :

To escape characters in format strings, you can wrap the characters in square brackets.

Since "Z" is a format token for the timezone, you need to escape it. So the format string you are after is:

moment().format('YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');

As @VincenzoC said in a comment, the toISOString() method would also give you the format you are after.

Use moment.utc() to display time in UTC time instead of local time:

var dateValue = moment().utc().format('YYYY-MM-DDTHH:mm:ss') + 'Z';

or moment().toISOString() to display a string in ISO format (format: YYYY-MM-DDTHH:mm:ss.sssZ, the timezone is always UTC):

var dateValue = moment().toISOString();

Try this

  const start_date = '2018-09-30'; const t = moment(start_date).utc().format(); console.log(t); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script> 

var dateTime = new Date("2015-06-17 14:24:36");
dateTime = moment(dateTime).format("YYYY-MM-DD HH:mm:ss");

Try this. You should have the date in the correct format.

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