[英]Javascript: Convert date to UTC format
I have the following date in UTC format: 2016-06-18T05:18:27.935Z
我具有以下UTC格式的日期:
2016-06-18T05:18:27.935Z
I am using the code below to convert it to the following format 2016-06-18 05:18:27
so I can compared it in MySQL
database against updatedAt
column. 我正在使用下面的代码将其转换为以下格式
2016-06-18 05:18:27
所以我可以将它在MySQL
数据库中与updatedAt
列进行比较。
var date = new Date(lastRequest);
date = date.getUTCFullYear() + '-' +
('00' + (date.getUTCMonth() + 1)).slice(-2) + '-' +
('00' + date.getUTCDate()).slice(-2) + ' ' +
('00' + date.getUTCHours()).slice(-2) + ':' +
('00' + date.getUTCMinutes()).slice(-2) + ':' +
('00' + date.getUTCSeconds()).slice(-2);
I need to get the date of the last record and convert its date back to UTC format. 我需要获取最后一条记录的日期,并将其日期转换回UTC格式。
Basically, how do I go from the following format: 2016-06-18 05:18:27
back to UTC? 基本上,我该如何从以下格式开始:
2016-06-18 05:18:27
回到UTC?
new Date('2016-06-18 05:18:27').toUTCString()
The toUTCString() method converts a date to a string, using the UTC time zone. toUTCString()方法使用UTC时区将日期转换为字符串。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString
And in fact, your format maybe the result of this: 实际上,您的格式可能是以下结果:
new Date('2016-06-18 05:18:27').toISOString()
And by the way, if you want to format the date, moment.js or fecha may be better. 顺便说一句,如果您要格式化日期, 那么moment.js或fecha可能更好。
You can also find similar answers in How do you convert a JavaScript date to UTC? 您还可以在如何将JavaScript日期转换为UTC中找到类似的答案。
Try this 尝试这个
var date = new Date(Date.now());
date = date.getUTCFullYear() + '-' +
('00' + (date.getUTCMonth() + 1)).slice(-2) + '-' +
('00' + date.getUTCDate()).slice(-2) + ' ' +
('00' + date.getUTCHours()).slice(-2) + ':' +
('00' + date.getUTCMinutes()).slice(-2) + ':' +
('00' + date.getUTCSeconds()).slice(-2);
print(date);
print(date.slice(0,10)+'T'+date.slice(11,19)+'.000Z');
2016-12-17 04:34:28 2016-12-17T04:34:28.000Z 2016-12-17 04:34:28 2016-12-17T04:34:28.000Z
http://rextester.com/SGDV59246 http://rextester.com/SGDV59246
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.