JS gets date in UTC

I created the date in JS like this:

var myDate = new Date('2013-01-01 00:00:00'); 

I guess JS reads this as UTC time. But when I do something like myDate.getTime (), the returned timestamp was something like the time at 4:00 GMT.

Why is this? And how do I get a date like midnight in UTC?

+4
source share
4 answers

At least in Chrome, this works:

var myDate = new Date('2013-01-01 00:00:00 UTC');

It also works if you put GMT instead of UTC . But I don't know if this is a cross browser enough.

+2
source

I live in India. So my time zone is Indian Standard Time (IST), which is listed in the tz database as Asia/Kolkata . India - 5 hours 30 minutes more than Greenwich. Therefore, when I execute new Date("2013-01-01 00:00:00") , the actual time in GMT is "2012-12-31 18:30:00" .

I believe that you live in America because you are in the EST time zone (GMT-04: 00)? I'm right?

If you want to analyze time in GMT instead of your local time zone, do the following:

 new Date("2013-01-01T00:00:00+00:00"); 

Note the capital T between date and time and +00:00 at the end. This is the format used to parse a specific time in a specific time zone.


Given the date string "2013-01-01 00:00:00" you can convert it to the required format using the following function:

 function formatDateString(string, timezone) { return string.replace(" ", "T") + timezone; } 

Then you can create the date as follows:

 new Date(formatDateString("2013-01-01 00:00:00", "+00:00")); 

Another way to convert local time to GMT:

 var timezone = new Date("1970-01-01 00:00:00"); // this is the start of unix time 

Now that you have your own time zone as a date object, you can do:

 new Date(new Date("2013-01-01 00:00:00") - timezone); 

All of the above methods return the same date in GMT.

+2
source

JS reads this with the time zone that your computer uses.

You can try using myDate.toUTCString() to get the date in UTC.

If you want to use the timestamp myDate.getTime()

0
source

Mine works just by doing it

 var datetime= new Date() 

However, the month is 1, so you need to add one

-1
source

Source: https://habr.com/ru/post/1490927/


All Articles