Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Parse UTC Date

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.

like image 657
Artem Kalinchuk Avatar asked Aug 27 '15 14:08

Artem Kalinchuk


People also ask

How do I convert date to UTC date?

To convert a JavaScript date object to a UTC string, you can use the toUTCString() method of the Date object. The toUTCString() method converts a date to a string, using the universal time zone. Alternatively, you could also use the Date. UTC() method to create a new Date object directly in UTC time zone.

Is new date () in UTC?

Browsers may differ, however, Date. getTime() returns the number of milliseconds since 1970-01-01. If you create a new Date using this number, ex: new Date(Date. getTime()); it will be UTC, however when you display it (ex: through the chrome dev tools console) it will appear to be your local timezone.

Does JavaScript date use UTC?

The Date. UTC() method in JavaScript is used to return the number of milliseconds in a Date object since January 1, 1970, 00:00:00, universal time. The UTC() method differs from the Date constructor in two ways: Date.

How can I get the current date and time in UTC or GMT in JavaScript?

JavaScript Date toUTCString() The toUTCString() method returns a date object as a string, according to UTC. Tip: The Universal Coordinated Time (UTC) is the time set by the World Time Standard. Note: UTC time is the same as GMT time.


1 Answers

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 
like image 115
potatopeelings Avatar answered Sep 29 '22 15:09

potatopeelings