JavaScript - Parse UTC Date
Asked Answered
H

5

54

How can I parse a simple date string and let JavaScript know that it's actually a UTC date? Currently, if I do new Date('2015-08-27') it converts it to my timezone.

Holliehollifield answered 27/8, 2015 at 14:46 Comment(4)
I strongly recommend using a library for thatHelsa
Many different options: #949032Saleswoman
I want to stay away from libraries.Holliehollifield
There is conversion, so your date might be the same .. You might not need to convert it to your timezone, what is the display of new Date('2015-08-27').toISOString()Southwestwards
H
48

You can do append 'T00:00:00.000Z' to make the time zone specific (Z indicates UTC)

new Date('2015-08-27' + 'T00:00:00.000Z')

Note that new Date('2015-08-27') is treated differently in ES5 (UTC) vs. ES6 (Local), so you can't expect it any correction to be work consistently if you were planning to to hard code it (i.e. don't do it)


Also, do note that your console.log might show you the local time corresponding to the UTC time the expression evaluates to (that tends to throw you off a bit if you are expecting UTC to be at the end for expression that evaluate to UTC times and your local time zone at the end for those that evaluate to your local time). For instance

new Date('2015-08-27T00:00:00.000Z')

could show

Thu Aug 27 2015 1:00:00 GMT+100

which is the same as

Thu Aug 27 2015 00:00:00 UTC
Hark answered 27/8, 2015 at 15:1 Comment(1)
would be nice to have a fully fledged solution dealing with many strings and options on Date instantiationBerger
L
6

In some cases, when other solutions don't work, adding GMT will help:

new Date('July 11, 2022, 16:22:14 PM' + ' GMT')

(note, an user below in comment, reports bug about this)

Liner answered 4/9, 2022 at 15:14 Comment(4)
Thanks, this works more often. For me, using a date formatted like mm/dd/yyyyT00:00:00.000Z as the suggested option suggested does not work. Using mm/dd/yyyy GMT absolutely works though. Should be the accepted answer imoImpunity
@Impunity that's because mm/dd/yyyyT00:00:00.000Z is not the correct format. It should be yyyy-mm-ddT00:00:00.000Z, and this does work.Saprogenic
@JohnC - it does not work for US/negative timezones. Using 2024-04-26T00:00:00Z actually creates and displays the date as april 25. (Chrome and FF). Currently the only way I can get the date I want is splitting on "-" and assembling a date from the parts.Finbur
@EmeryNoel that is because you are not including any time zone information in the string. You have Z, which tells the parser that the date is in UTC time zone. So, if you parse a date from UTC and then print it, it will print in your local time zone which will possibly be previous day if your local time zone is negative.Saprogenic
L
2

This might be obvious to most, but I got stumped for a few seconds because my string already had hh:mm:ss, so it required a little bit of string manipulation.

var d = '2022-09-14 13:20:31';
d = d.split(' ').join('T')+'Z';
var date = new Date(d);
console.log(date);

This version is more verbose, but feels sturdier to me.

var d = '2022-09-14 13:20:31';
var [yyyy, mm, dd, hh, m, s] = d.split(/[^\d]+/);
var date = new Date();
date.setUTCFullYear(+yyyy);
date.setUTCMonth(mm-1);
date.setUTCDate(+dd);
date.setUTCHours(+hh);
date.setUTCMinutes(+m);
date.setUTCSeconds(+s);
console.log(date);
Lyophobic answered 14/9, 2022 at 14:4 Comment(0)
S
0

These two helper functions move UTC date to local timezone and vice-versa

For your problem you would call: datetimeToUTC(new Date('2015-08-27')).


/** If you parsed a date without time zone, you may need to shift it to local time */
function datetimeToLocal(fromDate) {
  return new Date(
    fromDate.getUTCFullYear(),
    fromDate.getUTCMonth(),
    fromDate.getUTCDate(),
    fromDate.getUTCHours(),
    fromDate.getUTCMinutes(),
    fromDate.getUTCSeconds(),
    fromDate.getUTCMilliseconds(),
  )
}

/** If you parsed a date without time zone, you may need to shift it to UTC time */
function datetimeToUTC(fromDate) {
  return new Date(Date.UTC(
    fromDate.getFullYear(),
    fromDate.getMonth(),
    fromDate.getDate(),
    fromDate.getHours(),
    fromDate.getMinutes(),
    fromDate.getSeconds(),
    fromDate.getMilliseconds(),
  ))
}

The implementation is part of the zeed library (MIT).

Sequestered answered 6/4 at 12:39 Comment(0)
M
-5

Here is what I would do.

var current = new Date();
var utcDate = new Date(current.getTime() + current.getTimezoneOffset() * 60000);
Mauchi answered 27/8, 2015 at 14:51 Comment(2)
time zone offsets are not always given in values divisible by one hour. Iceland, for instance, has a half-hour time zone offset.Gagliardi
@JonTrauntvein Iceland uses GMT without any daylight savings. Delhi uses the UTC+5:30 however, if you're looking for a non-hourly timezone. There don't seem to be any countries observing UTC+0:30 although some have in the past.Adrien

© 2022 - 2024 — McMap. All rights reserved.