UNPKG

web-ui-pack

Version:
84 lines (83 loc) 2.74 kB
import dateToString, { zeroBefore } from "../helpers/dateToString"; import localeInfo from "./localeInfo"; export default class WUPTimeObject { hours; minutes; static $maxValue = 23 * 60 + 59; constructor(...args) { this.hours = 0; this.minutes = 0; let isPM = null; if (args.length === 1) { if (typeof args[0] === "string") { const [h, m] = args[0].split(/\W/); this.hours = Number.parseInt(h, 10); this.minutes = Number.parseInt(m, 10); if (/[pP][mM]$/.test(args[0])) { isPM = true; } else if (/[aA][mM]$/.test(args[0])) { isPM = false; } } else { this.hours = Math.floor(args[0] / 60); this.minutes = args[0] - this.hours * 60; } } else if (args.length >= 2) { if (args.length === 2 && typeof args[0] === "object") { const u = args[1] ? "UTC" : ""; this.hours = args[0][`get${u}Hours`](); this.minutes = args[0][`get${u}Minutes`](); } else { this.hours = args[0]; this.minutes = args[1]; isPM = args[2]; } } const h12Invalid = isPM != null && (this.hours < 1 || this.hours > 12); if (this.hours === 12 && isPM === false) { this.hours = 0; } else if (this.hours !== 12 && isPM === true) { this.hours += 12; } if (h12Invalid || Number.isNaN(this.hours) || Number.isNaN(this.minutes) || this.hours < 0 || this.hours > 23 || this.minutes < 0 || this.minutes > 59) { const err = RangeError("Out of range"); err.details = { parsed: this, args }; console.warn(`${err.message}. Details:`, err.details); throw err; } } copyToDate(dt, isUTC) { const ukey = isUTC ? "UTC" : ""; dt[`set${ukey}Hours`](this.hours, this.minutes, 0, 0); return dt; } valueOf() { return this.hours * 60 + this.minutes; } get isPM() { return this.hours > 11; } toString(sep = ":") { return `${zeroBefore(this.hours, 2)}${sep}${zeroBefore(this.minutes, 2)}`; } toLocaleString() { return this.format(localeInfo.time); } format(format) { return dateToString(new Date(1, 1, 1, this.hours, this.minutes), format.replace(/[\D\W]ss/, "")); } toJSON() { return `${this.hours}:${this.minutes}`; } }