luxon
Version:
Immutable date wrapper
98 lines (84 loc) • 2.15 kB
JavaScript
import { padStart, signedOffset } from "../impl/util.js";
import Zone from "../zone.js";
let singleton = null;
function hoursMinutesOffset(z) {
const hours = Math.trunc(z.fixed / 60),
minutes = Math.abs(z.fixed % 60),
sign = hours > 0 ? "+" : "-",
base = sign + Math.abs(hours);
return minutes > 0 ? `${base}:${padStart(minutes, 2)}` : base;
}
/**
* A zone with a fixed offset (i.e. no DST)
* @implements {Zone}
*/
export default class FixedOffsetZone extends Zone {
/**
* Get a singleton instance of UTC
* @return {FixedOffsetZone}
*/
static get utcInstance() {
if (singleton === null) {
singleton = new FixedOffsetZone(0);
}
return singleton;
}
/**
* Get an instance with a specified offset
* @param {number} offset - The offset in minutes
* @return {FixedOffsetZone}
*/
static instance(offset) {
return offset === 0 ? FixedOffsetZone.utcInstance : new FixedOffsetZone(offset);
}
/**
* Get an instance of FixedOffsetZone from a UTC offset string, like "UTC+6"
* @param {string} s - The offset string to parse
* @example FixedOffsetZone.parseSpecifier("UTC+6")
* @example FixedOffsetZone.parseSpecifier("UTC+06")
* @example FixedOffsetZone.parseSpecifier("UTC-6:00")
* @return {FixedOffsetZone}
*/
static parseSpecifier(s) {
if (s) {
const r = s.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);
if (r) {
return new FixedOffsetZone(signedOffset(r[1], r[2]));
}
}
return null;
}
constructor(offset) {
super();
/** @private **/
this.fixed = offset;
}
/** @override **/
get type() {
return "fixed";
}
/** @override **/
get name() {
return this.fixed === 0 ? "UTC" : `UTC${hoursMinutesOffset(this)}`;
}
/** @override **/
offsetName() {
return this.name;
}
/** @override **/
get universal() {
return true;
}
/** @override **/
offset() {
return this.fixed;
}
/** @override **/
equals(otherZone) {
return otherZone.type === "fixed" && otherZone.fixed === this.fixed;
}
/** @override **/
get isValid() {
return true;
}
}