0

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 compared 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?

user1107173
  • 10,334
  • 16
  • 72
  • 117

2 Answers2

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.org/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?

Community
  • 1
  • 1
SkyAo
  • 647
  • 1
  • 4
  • 13
  • I think the OP was trying to get **from** the UTC time string back **to** a javascript `Date`. – 2ps Dec 17 '16 at 04:34
  • 1
    @2ps Well, by `new Date()`, everything will be ok. But I think store `string` ( maybe `varchar`? )for date is the mistake, in fact `timestamp` is a better type in MySQL. – SkyAo Dec 17 '16 at 04:39
  • Note that moment.js is not recommended anymore these days: https://momentjs.com/docs/#/-project-status/ – rethab Jul 22 '21 at 06:26
1

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.com/SGDV59246

  • Thank you! Is there a way to retain the same `.000Z` value? i.e. original was `2016-06-18T05:18:27.935Z` and after using your solution, it's `2016-06-18T05:18:27.000Z` – user1107173 Dec 17 '16 at 20:58