UNPKG

ravendb

Version:
76 lines 2.7 kB
import { throwError } from "../Exceptions/index.js"; import { format, parse, parseISO } from "date-fns"; export class DateUtil { opts; static DEFAULT_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'0000'"; static DEFAULT_DATE_TZ_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'0000'xxx"; static default = new DateUtil({}); static utc = new DateUtil({ useUtcDates: true }); static tz = new DateUtil({ withTimezone: true }); constructor(opts) { this.opts = opts; } static timestamp() { return Math.floor(new Date().getTime() / 1000); } static timestampMs() { return new Date().getTime(); } static zeroDate() { return new Date(0); } parse(dateString) { if (!dateString) { return null; } dateString = DateUtil.alignPrecision(dateString); let parsed; if (this.opts.withTimezone) { parsed = parse(dateString, DateUtil.DEFAULT_DATE_TZ_FORMAT, new Date()); } else if (this.opts.useUtcDates || dateString.endsWith("Z")) { if (!dateString.endsWith("Z")) { dateString += "Z"; } parsed = parseISO(dateString); } else { parsed = parse(dateString, DateUtil.DEFAULT_DATE_FORMAT, new Date()); } if (isNaN(parsed.getTime())) { throwError("InvalidArgumentException", `Could not parse date string '${dateString}'.`); } return parsed; } static alignPrecision(date) { const hasZ = date.endsWith("Z"); if (hasZ) { date = date.slice(0, -1); } const lastDot = date.lastIndexOf("."); const tzPlusIndex = date.indexOf("+", lastDot); const tzMinusIndex = date.indexOf("-", lastDot); const tzIndex = Math.max(tzPlusIndex, tzMinusIndex); let tzSuffix = ""; if (tzIndex !== -1) { tzSuffix = date.substring(tzIndex); date = date.slice(0, tzIndex - 1); } const suffix = "0000" + tzSuffix + (hasZ ? "Z" : ""); if (lastDot === -1 || lastDot < date.length - 3) { return date.slice(0, lastDot + 4) + suffix; } return date + suffix; } stringify(date) { if (this.opts.useUtcDates) { const utcString = date.toISOString().slice(0, -1); return this.opts.withTimezone ? utcString + "0000+00:00" : utcString + "0000Z"; } const dateFormat = this.opts.withTimezone ? DateUtil.DEFAULT_DATE_TZ_FORMAT : DateUtil.DEFAULT_DATE_FORMAT; return format(date, dateFormat); } } //# sourceMappingURL=DateUtil.js.map