Ad

Build Date Object From String And Timezone

I'm looking for a way to build a correct Date object given a date/time string and a timezone.

Currently I have a list of timezones with the specific offset and want to merge them simply together like this:

new Date(`${date} ${time} GMT${offset}`);
// new Date('2019-08-30 10:00:00 GMT+0100`);

But doing it like this doesn't care about dst and I get an date, which is in the summer one hour ahead.

Ad

Answer

If you have the offset, you can build a string in the JavaScript date time format and use that with new Date. The format looks like this: 2019-08-30T10:00:00+0100.

It looks like your offset is the string "+0100". If so:

new Date(`${date}T${time}${offset}`);

Live Example:

const date = "2019-08-30";
const time = "10:00:00";
const offset = "+0100";

const dt = new Date(`${date}T${time}${offset}`);
console.log("toISOString:", dt.toISOString());
console.log("toLocaleString", dt.toLocaleString());

In my timezone (British Summer Time, GMT+0100) with Chrome (V8), that outputs:

toISOString: 2019-08-30T09:00:00.000Z
toLocaleString 30/08/2019, 10:00:00

...which makes sense, 10:00:00 BST is 09:00:00 GMT.

But doing it like this doesn't care about dst and I get an date, which is in the summer one hour ahead.

Correct. You need to provide the correct offset for the date. Your list of timezones should have DST information (if not, it's incomplete and, unfortunately, fairly useless). To do that properly you need to use the a proper timezone database such as the IANA one. Your best bet for that isn't to do it yourself, but to use a library that does it for you, such as Moment timezone or the one you found, spacetime. But yes, you could use those database files directly, they're accessible from the link above. But note that common timezone shorthand terms like "BST" (for British Summer Time) or "EDT" (for U.S. Eastern Daylight Time) are not standardized in any way. The IANA database uses zones like Europe/London(insert Brexit joke here).

Ad
source: stackoverflow.com
Ad