chronoshift
Version:
A tiny library for shifting time with timezones
60 lines (59 loc) • 1.8 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.Timezone = void 0;
const date_1 = require("@internationalized/date");
class Timezone {
static formatDateWithTimezone(d, timezone) {
let str;
if (timezone && !timezone.isUTC()) {
str = (0, date_1.fromDate)(d, timezone.toString()).toString().replace(/\[.+$/, '');
}
else {
str = d.toISOString();
}
return str.replace('.000', '');
}
static fromJS(spec) {
return new Timezone(spec);
}
constructor(timezone) {
if (typeof timezone !== 'string') {
throw new TypeError('timezone description must be a string');
}
if (timezone !== 'Etc/UTC') {
try {
(0, date_1.fromDate)(new Date(), timezone);
}
catch (_a) {
throw new Error(`timezone '${timezone}' does not exist`);
}
}
this.timezone = timezone;
}
valueOf() {
return this.timezone;
}
toJS() {
return this.timezone;
}
toJSON() {
return this.timezone;
}
toString() {
return this.timezone;
}
equals(other) {
return other instanceof Timezone && this.timezone === other.timezone;
}
isUTC() {
return this.timezone === 'Etc/UTC';
}
toUtcOffsetString() {
const utcOffset = (0, date_1.fromDate)(new Date(), this.toString()).offset;
const hours = String(Math.abs(Math.floor(utcOffset / 60))).padStart(2, '0');
const minutes = String(Math.abs(utcOffset % 60)).padStart(2, '0');
return `UTC ${utcOffset >= 0 ? '+' : '-'}${hours}:${minutes}`;
}
}
exports.Timezone = Timezone;
Timezone.UTC = new Timezone('Etc/UTC');
;