Skip to content
Advertisement

Ignore timezone when creating Date from numeric values

Simple example:

new Date(2018,0,1,0,0,0,0)

Produces 2017-12-31T23:00:00.000Z where I’m at (GMT+1). I am creating dates from string values in the following format:

YYYYMMDD HHmm
20170326 0135

These come from weather data at ftp://ftp.ncdc.noaa.gov/pub/data/uscrn/products/subhourly01/2017/. Now I tried to workaround the timeout issue by adding one to hours, eg.: new Date(2018,0,1,0+1,0,0,0)->2018-01-01T00:00:00.000Z

But that fails if you want to make date near midnight, since adding 1 to 23:30, for example, creates 24:30 which is invalid value. The result will be midnight the same day, not 1’o clock the next day:

new Date(2018,0,1,23+1,30,0,0)
2018-01-01T23:30:00.000Z

Also, for some reason, Date substracts 2 hours from some times:

new Date(2017, 2, 26, 3, 0, 0, 0);
2017-03-26T01:00:00.000Z

So this question is – how do I create date ignoring timezones so that I can create it from local datetime strings.

Advertisement

Answer

You can use Date.UTC function which returns UTC timestamp:

new Date(Date.UTC(2018, 0, 1, 23, 30, 0, 0))

By the way, 24:30 is completely valid for the JS date. It will correctly overflow to the next day.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement