localized-dst
Version:
Determine if a date is in daylight savings time by country/state/city
82 lines (81 loc) • 2.81 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.isDst = exports.getDstRef = void 0;
const date_fns_1 = require("date-fns");
const moment = require("moment-timezone");
const canada_dst_1 = require("./dst/canada-dst");
const france_dst_1 = require("./dst/france-dst");
const usa_dst_1 = require("./dst/usa-dst");
const getCountryDstRef = (country) => {
switch (country) {
case 'CAN':
return canada_dst_1.default;
case 'FRA':
return france_dst_1.default;
case 'USA':
return usa_dst_1.default;
default:
null;
}
};
const getDstRef = (location, failIfNotExisting = false) => {
const [country, state, city] = location.split('.');
const countryRef = getCountryDstRef(country);
if (!countryRef || (countryRef && !countryRef.defaultDstRef)) {
const message = `Refs don't exist for this ISO country code (${country})`;
if (failIfNotExisting) {
throw new Error(message);
}
else {
console.warn(message);
return null;
}
}
if (!state) {
return countryRef.defaultDstRef;
}
if ((state && !countryRef.states) || (state && !countryRef.states[state])) {
const message = `State (${state}) doesn't exist for this ISO country code (${country})`;
if (failIfNotExisting) {
throw new Error(message);
}
else {
console.warn(message);
return null;
}
}
if (!city) {
return countryRef.states[state].defaultDstRef;
}
if ((city && !countryRef.states[state].cities) ||
(city && !countryRef.states[state].cities[city])) {
const message = `City (${city}) doesn't exist for "${country}/${state}"`;
if (failIfNotExisting) {
throw new Error(message);
}
else {
console.warn(message);
return null;
}
}
return countryRef.states[state].cities[city].defaultDstRef;
};
exports.getDstRef = getDstRef;
const isDst = (date, options) => {
const refs = exports.getDstRef(options.location, options.failIfNotExisting);
const currentYear = date_fns_1.getYear(date);
const { refs: dates, timezone } = refs;
if (!dates[currentYear] || !currentYear) {
const message = `DST doesn't exist for this year (${currentYear})`;
if (options.failIfNotExisting) {
throw new Error(message);
}
else {
console.warn(message);
return false;
}
}
return (date_fns_1.isAfter(date, moment.tz(dates[currentYear][0], timezone).toDate()) &&
date_fns_1.isBefore(date, moment.tz(dates[currentYear][1], timezone).toDate()));
};
exports.isDst = isDst;