@tubular/time
Version:
Date/time, IANA timezones, leap seconds, TAI/UTC conversions, calendar with settable Julian/Gregorian switchover
272 lines (268 loc) • 12.4 kB
JavaScript
/*
Copyright © 2017-2021 Kerry Shetline, kerry@shetline.com
MIT license: https://opensource.org/licenses/MIT
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { DAY_MSEC } from './common';
import { DateTime } from './date-time';
import { newDateTimeFormat } from './format-parse';
import { Timezone } from './timezone';
import timezoneSmall from './timezone-small';
import timezoneLarge from './timezone-large';
import timezoneLargeAlt from './timezone-large-alt';
import { parse } from './format-parse';
import { forEach, isBoolean, isString, toNumber } from '@tubular/util';
import { CalendarType, DayOfWeek, Month, LAST } from './calendar';
import { getDeltaTAtJulianDate, tdtToUt, utToTdt } from './ut-converter';
import { defaultLocale, getMinDaysInWeek, getStartOfWeek, getWeekend, hasDateTimeStyle, hasIntlDateTime } from './locale-data';
let win = null;
let zonesDefined = false;
let defineAttempts = 0;
try {
win = window;
}
catch (_a) { }
function initialZoneDefine() {
var _a, _b, _c;
const initZones = (_c = (_b = (_a = win === null || win === void 0 ? void 0 : win.tbTime_timezone_large) !== null && _a !== void 0 ? _a : win === null || win === void 0 ? void 0 : win.tbTime_timezone_large_alt) !== null && _b !== void 0 ? _b : timezoneSmall) !== null && _c !== void 0 ? _c : win === null || win === void 0 ? void 0 : win.tbTime_timezone_small;
if (!initZones && ++defineAttempts < 20)
setTimeout(initialZoneDefine, 100);
else {
Timezone.defineTimezones(initZones);
zonesDefined = !!initZones;
if (win) {
delete win.tbTime_timezone_large;
delete win.tbTime_timezone_large_alt;
delete win.tbTime_timezone_small;
}
}
}
initialZoneDefine();
export { Calendar, CalendarType, dateAndTimeFromMillis_SGC, DayOfWeek, Month, GREGORIAN_CHANGE_MAX_YEAR, GREGORIAN_CHANGE_MIN_YEAR, SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, LAST, getISOFormatDate, addDaysToDate_SGC, getDateFromDayNumber_SGC, getDateFromDayNumberGregorian, getDateFromDayNumberJulian, getDateOfNthWeekdayOfMonth_SGC, getDayNumber_SGC, getDayNumberGregorian, getDayNumberJulian, getDayOfWeek, getDayOfWeek_SGC, getDayOfWeekInMonthCount_SGC, getDayOnOrAfter_SGC, getDayOnOrBefore_SGC, getDaysInMonth_SGC, getDaysInYear_SGC, getFirstDateInMonth_SGC, getLastDateInMonth_SGC, getLastDateInMonthGregorian, getLastDateInMonthJulian, isJulianCalendarDate_SGC, isValidDate_SGC, isValidDateGregorian, isValidDateJulian, millisFromDateTime_SGC, parseISODate } from './calendar';
export { MINUTE_MSEC, DAY_MINUTES, DAY_MSEC, HOUR_MSEC, parseISODateTime, parseTimeOffset } from './common';
export { DateTime, DateTimeField } from './date-time';
export { newDateTimeFormat } from './format-parse';
export { defaultLocale, getMinDaysInWeek, getStartOfWeek, getWeekend, hasDateTimeStyle, hasIntlDateTime } from './locale-data';
export { getDeltaTAtJulianDate, utToTaiMillis, utToTdt, taiToUtMillis, tdtToUt } from './ut-converter';
export { Timezone } from './timezone';
export { zonePollerBrowser } from './zone-poller-browser';
export { zonePollerNode } from './zone-poller-node';
export { isSafeTaiMillis, isSafeUtcMillis } from './ut-converter';
export function initTimezoneSmall() {
Timezone.defineTimezones(timezoneSmall !== null && timezoneSmall !== void 0 ? timezoneSmall : win === null || win === void 0 ? void 0 : win.tbTime_timezone_small);
}
export function initTimezoneLarge(failQuietly = false) {
var _a;
const zones = (_a = timezoneLarge !== null && timezoneLarge !== void 0 ? timezoneLarge : win === null || win === void 0 ? void 0 : win.tbTime_timezone_large) !== null && _a !== void 0 ? _a : win === null || win === void 0 ? void 0 : win.tbTime_tzcache_large;
if (zones)
Timezone.defineTimezones(zones);
else {
const msg = 'Large timezone definitions unavailable. Falling back to defaults.';
console.error(msg);
Timezone.defineTimezones(timezoneSmall);
if (!failQuietly)
throw new Error(msg);
}
}
export function initTimezoneLargeAlt(failQuietly = false) {
var _a;
const zones = (_a = timezoneLargeAlt !== null && timezoneLargeAlt !== void 0 ? timezoneLargeAlt : win === null || win === void 0 ? void 0 : win.tbTime_timezone_large_alt) !== null && _a !== void 0 ? _a : win === null || win === void 0 ? void 0 : win.tbTime_tzcache_large_alt;
if (zones)
Timezone.defineTimezones(zones);
else {
const msg = 'Large-Alt timezone definitions unavailable. Falling back to defaults.';
console.error(msg);
Timezone.defineTimezones(timezoneSmall);
if (!failQuietly)
throw new Error(msg);
}
}
let pollingInterval;
let lastUpdateName = 'small';
let currentTzVersion = Timezone.version === 'unspecified' ? '' : Timezone.version;
const versionCheckUrl = 'https://tzexplorer.org/api/tz-version';
const zonesUrl1 = 'https://unpkg.com/@tubular/time/dist/data/timezone-{name}.js';
const zonesUrl2 = 'https://tzexplorer.org/tzdata/timezone-{name}.js';
export function pollForTimezoneUpdates(zonePoller, name = 'small', intervalDays = 1) {
if (pollingInterval)
clearInterval(pollingInterval);
if (zonePoller && name && intervalDays >= 0) {
const poll = async () => {
let latestTzVersion;
try {
latestTzVersion = await zonePoller.getLatestVersion(versionCheckUrl);
}
catch (e) {
dispatchUpdateNotification(e);
return;
}
if (latestTzVersion <= currentTzVersion && lastUpdateName === name) {
dispatchUpdateNotification(false);
return;
}
let zones;
let updated = false;
try {
zones = await zonePoller.getTimezones(zonesUrl1.replace('{name}', name));
updated = Timezone.defineTimezones(zones);
}
catch (_a) { }
if (!updated) {
try {
zones = await zonePoller.getTimezones(zonesUrl2.replace('{name}', name));
updated = Timezone.defineTimezones(zones);
}
catch (e) {
dispatchUpdateNotification(e);
return;
}
}
if (updated)
currentTzVersion = latestTzVersion;
lastUpdateName = name;
dispatchUpdateNotification(updated);
};
poll().finally();
if (intervalDays > 0) {
pollingInterval = setInterval(poll, Math.max(intervalDays * DAY_MSEC, 3600000));
// Using unref prevents the interval alone from keeping a process alive
if (pollingInterval.unref)
pollingInterval.unref();
}
}
}
export async function getTimezones(zonePoller, name = 'small') {
return new Promise((resolve, reject) => {
const listener = (result) => {
removeZonesUpdateListener(listener);
if (result instanceof Error)
reject(result);
else
resolve(result);
};
addZonesUpdateListener(listener);
pollForTimezoneUpdates(zonePoller, name, 0);
});
}
const listeners = new Set();
function dispatchUpdateNotification(result) {
if (!(result instanceof Error) && !isBoolean(result))
result = new Error(String(result)); // Oddly, some errors come through as numbers like 404.
listeners.forEach(listener => {
try {
listener(result);
}
catch (e) {
console.error(e);
}
});
}
export function addZonesUpdateListener(listener) {
listeners.add(listener);
}
export function removeZonesUpdateListener(listener) {
listeners.delete(listener);
}
export function clearZonesUpdateListeners() {
listeners.clear();
}
export function isDateTime(obj) { return obj instanceof DateTime; }
export function isDate(obj) { return obj instanceof Date; }
export function unix(seconds, zone) {
return new DateTime(Math.round(seconds * 1000), zone).lock();
}
export function max(...dates) {
let result = dates[0];
for (let i = 1; i < dates.length; ++i) {
if (DateTime.milliCompare(dates[i], result) > 0)
result = dates[i];
}
return result;
}
export function min(...dates) {
let result = dates[0];
for (let i = 1; i < dates.length; ++i) {
if (DateTime.milliCompare(dates[i], result) < 0)
result = dates[i];
}
return result;
}
export function sort(dates, descending = false) {
if (dates)
dates.sort((a, b) => DateTime.compare(a, b) * (descending ? -1 : 1));
return dates;
}
export function ttime(initialTime, format, locale) {
var _a;
if (!format || !isString(initialTime))
return new DateTime(initialTime, null, locale).lock();
else
return (_a = parse(initialTime, format, null, locale)) === null || _a === void 0 ? void 0 : _a.lock();
}
ttime.addZonesUpdateListener = addZonesUpdateListener;
ttime.clearZonesUpdateListeners = clearZonesUpdateListeners;
ttime.getTimezones = getTimezones;
ttime.initTimezoneSmall = initTimezoneSmall;
ttime.initTimezoneLarge = initTimezoneLarge;
ttime.initTimezoneLargeAlt = initTimezoneLargeAlt;
ttime.isDateTime = isDateTime;
ttime.isDate = isDate;
ttime.max = max;
ttime.min = min;
ttime.unix = unix;
ttime.parse = parse;
ttime.pollForTimezoneUpdates = pollForTimezoneUpdates;
ttime.removeZonesUpdateListener = removeZonesUpdateListener;
ttime.sort = sort;
ttime.DATETIME_LOCAL = 'Y-MM-DD[T]HH:mm';
ttime.DATETIME_LOCAL_SECONDS = 'Y-MM-DD[T]HH:mm:ss';
ttime.DATETIME_LOCAL_MS = 'Y-MM-DD[T]HH:mm:ss.SSS';
ttime.DATE = 'Y-MM-DD';
ttime.TIME = 'HH:mm';
ttime.TIME_SECONDS = 'HH:mm:ss';
ttime.TIME_MS = 'HH:mm:ss.SSS';
ttime.WEEK = 'GGGG-[W]WW';
ttime.WEEK_AND_DAY = 'GGGG-[W]WW-E';
ttime.WEEK_LOCALE = 'gggg-[w]ww';
ttime.WEEK_AND_DAY_LOCALE = 'gggg-[w]ww-e';
ttime.MONTH = 'Y-MM';
ttime.PURE_JULIAN = CalendarType.PURE_JULIAN;
ttime.PURE_GREGORIAN = CalendarType.PURE_GREGORIAN;
ttime.getDefaultCenturyBase = DateTime.getDefaultCenturyBase;
ttime.setDefaultCenturyBase = DateTime.setDefaultCenturyBase;
ttime.getDefaultLocale = DateTime.getDefaultLocale;
ttime.setDefaultLocale = DateTime.setDefaultLocale;
ttime.getDefaultTimezone = DateTime.getDefaultTimezone;
ttime.setDefaultTimezone = DateTime.setDefaultTimezone;
ttime.julianDay = DateTime.julianDay;
ttime.millisFromJulianDay = DateTime.millisFromJulianDay;
ttime.julianDay_SGC = DateTime.julianDay_SGC;
ttime.getDeltaTAtJulianDate = getDeltaTAtJulianDate;
ttime.newDateTimeFormat = newDateTimeFormat;
ttime.tdtToUt = tdtToUt;
ttime.utToTdt = utToTdt;
ttime.defaultLocale = defaultLocale;
ttime.getMinDaysInWeek = getMinDaysInWeek;
ttime.getStartOfWeek = getStartOfWeek;
ttime.getWeekend = getWeekend;
ttime.hasDateTimeStyle = hasDateTimeStyle;
ttime.hasIntlDateTime = hasIntlDateTime;
forEach(DayOfWeek, (key, value) => { if (toNumber(key, -1) < 0)
ttime[key] = value; });
forEach(Month, (key, value) => { if (toNumber(key, -1) < 0)
ttime[key] = value; });
ttime.LAST = LAST;
Object.freeze(ttime);
if (!zonesDefined && timezoneSmall)
initTimezoneSmall();
export default ttime;
//# sourceMappingURL=index.js.map