简体   繁体   中英

Daylight Savings Timezone Detection From Strings In JavaScript

I've looked in several places but I could not find a solution to this problem. I have some data I'm trying to import and for my case, it contains strings representing dates which are in the Eastern Time Zone (ET). Strings look like this:

July 28, 2018 03:39 PM

If I try to create a new date object in JavaScript, I can create the new date object, but the problem is that there is no ET timezone, so I can create it either using EST (Eastern Standard Time) or EDT (Eastern Daylight Time).

console.log(new Date('July 28, 2018 03:39 PM EST'));
2018-07-28T19:39:00.000Z

Or

console.log(new Date('July 28, 2018 03:39 PM EDT'));
2018-07-28T20:39:00.000Z

We can clearly see there is one hour difference between both. The rules to determine if Daylight Saving is active or not seems quite complex and can vary from geographic region.

So my question is: is there any solution out there which can detect the applicable time zone (daylight or standard) based on certain parameters? I presume at the minimum, the year, the month, the day, the time and standard time zone would be required?

I could not find any solution to this problem since JavaScript stores all date in UTC. Unless I can find the standard/daylight saving timezone of the string I'm parsing, I cannot reliably create a date object.

I could easily solve it for Eastern Time but, I am sure something better exists out there to solve it for all time zones?

The type of solution I would be looking for would look something like this:

let dateString = 'July 28, 2018 03:39 PM'
let timeZone = getStandardOrDaylightSavingsTZ(dateString, 'EST');
// "timeZone" would be set back to EDT right now because it's daylight savings
console.log(new Date(dateString + ' ' + timeZone));
2018-07-28T20:39:00.000Z

You could try moment-timezone . Given the complexity of timezone rules, a library is almost certainly in order.

In the example below, assume each date string came from the same server, which we know to be set to ET. We set the timezone in the constructor, and given where the parsed date falls on the calendar, and what the timezone rules are for that locale, it returns the correct time.

Output as ISO to verify.

var moment = require('moment-timezone');

var dates = [
    'March 10, 2018 03:39 PM',
    'March 11, 2018 03:39 PM',
];

for (let d of dates) {
    iso = moment.tz(d, "MMMM DD, YYYY hh:mm A", "America/Toronto").toISOString();
    console.log(iso);
}

// Daylight saving time began at 3:00 a.m. on Sunday, March 11
// 2018-03-10T20:39:00.000Z
// 2018-03-11T19:39:00.000Z

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM