简体   繁体   English

在Moment JS中以特定格式获取日期时间

[英]Get date time in specific format in moment js

I am trying to get the date time in moment js in this format : 我试图以这种格式获取时刻js中的日期时间:

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]. 但我需要第一个格式[例如.672Z,而不是+05:30]。 Any suggestions would be of great help. 任何建议都会有很大帮助。

From the documentation on the format method : 有关format方法文档中

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. 由于“ Z”是时区的格式标记,因此您需要对其进行转义。 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. 就像@VincenzoC在评论中说的那样, toISOString()方法还可以为您提供所需的格式。

Use moment.utc() to display time in UTC time instead of local time: 使用moment.utc()以UTC时间而不是本地时间显示时间:

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): 或moment()。toISOString()以显示ISO格式的字符串(格式:YYYY-MM-DDTHH:mm:ss.sssZ,时区始终为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. 您应该以正确的格式显示日期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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