admin管理员组

文章数量:1355602

I have the following date in UTC format: 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 pared it in MySQL database against updatedAt column.

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.

Basically, how do I go from the following format: 2016-06-18 05:18:27 back to UTC?

I have the following date in UTC format: 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 pared it in MySQL database against updatedAt column.

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.

Basically, how do I go from the following format: 2016-06-18 05:18:27 back to UTC?

Share Improve this question asked Dec 17, 2016 at 4:12 user1107173user1107173 10.8k17 gold badges75 silver badges121 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3
new Date('2016-06-18 05:18:27').toUTCString()

The toUTCString() method converts a date to a string, using the UTC time zone.

https://developer.mozilla/en-US/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.

You can also find similar answers in How do you convert a JavaScript date to 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

http://rextester./SGDV59246

本文标签: mysqlJavascript Convert date to UTC formatStack Overflow