Launch Week Day 5: Introducing Reachability for PHP.Learn More
Socket
Book a DemoSign in
Socket

@formkit/tempo

Package Overview
Dependencies
Maintainers
4
Versions
22
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@formkit/tempo - npm Package Compare versions

Comparing version
0.0.19
to
0.1.0
+9
dist/addDay.d.ts
import { DateInput } from './types.js';
/**
* Returns a new date object 1/n days after the original one.
* @param inputDate - A date to increment by 1 day.
*/
declare function addDay(inputDate: DateInput, count?: number): Date;
export { addDay };
// src/addDay.ts
import { date } from "./date.mjs";
function addDay(inputDate, count = 1) {
const d = date(inputDate);
d.setDate(d.getDate() + count);
return d;
}
export {
addDay
};
//# sourceMappingURL=addDay.mjs.map
{"version":3,"sources":["../src/addDay.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Returns a new date object 1/n days after the original one.\n * @param inputDate - A date to increment by 1 day.\n */\nexport function addDay(inputDate: DateInput, count = 1) {\n const d = date(inputDate)\n d.setDate(d.getDate() + count)\n return d\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAOd,SAAS,OAAO,WAAsB,QAAQ,GAAG;AACtD,QAAM,IAAI,KAAK,SAAS;AACxB,IAAE,QAAQ,EAAE,QAAQ,IAAI,KAAK;AAC7B,SAAO;AACT;","names":[]}
import { DateInput } from './types.js';
/**
* Returns a new date object 1/n hours after the original one.
* @param inputDate - A date to increment by 1 day.
*/
declare function addHour(inputDate: DateInput, count?: number): Date;
export { addHour };
// src/addHour.ts
import { date } from "./date.mjs";
function addHour(inputDate, count = 1) {
const d = date(inputDate);
d.setHours(d.getHours() + count);
return d;
}
export {
addHour
};
//# sourceMappingURL=addHour.mjs.map
{"version":3,"sources":["../src/addHour.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Returns a new date object 1/n hours after the original one.\n * @param inputDate - A date to increment by 1 day.\n */\nexport function addHour(inputDate: DateInput, count = 1) {\n const d = date(inputDate)\n d.setHours(d.getHours() + count)\n return d\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAOd,SAAS,QAAQ,WAAsB,QAAQ,GAAG;AACvD,QAAM,IAAI,KAAK,SAAS;AACxB,IAAE,SAAS,EAAE,SAAS,IAAI,KAAK;AAC/B,SAAO;AACT;","names":[]}
import { DateInput } from './types.js';
/**
* Returns a new date object 1/n seconds after the original one.
* @param inputDate - A date to increment by 1 day.
*/
declare function addMinute(inputDate: DateInput, count?: number): Date;
export { addMinute };
// src/addMinute.ts
import { date } from "./date.mjs";
function addMinute(inputDate, count = 1) {
const d = date(inputDate);
d.setMinutes(d.getMinutes() + count);
return d;
}
export {
addMinute
};
//# sourceMappingURL=addMinute.mjs.map
{"version":3,"sources":["../src/addMinute.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Returns a new date object 1/n seconds after the original one.\n * @param inputDate - A date to increment by 1 day.\n */\nexport function addMinute(inputDate: DateInput, count = 1) {\n const d = date(inputDate)\n d.setMinutes(d.getMinutes() + count)\n return d\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAOd,SAAS,UAAU,WAAsB,QAAQ,GAAG;AACzD,QAAM,IAAI,KAAK,SAAS;AACxB,IAAE,WAAW,EAAE,WAAW,IAAI,KAAK;AACnC,SAAO;AACT;","names":[]}
import { DateInput } from './types.js';
/**
* Returns a new date object 1/n months after the original one. Keep in mind if you
* start with a date late in a given month you could get a date after the next
* month.
* @param inputDate - A date to increment by 1 or more months.
* @param count - The quantity to add.
* @param dateOverflow - Whether or not to allow the date to overflow to another month if the inputDate’s month is out of range of the new month.
*/
declare function addMonth(inputDate: DateInput, count?: number, dateOverflow?: boolean): Date;
export { addMonth };
// src/addMonth.ts
import { date } from "./date.mjs";
import { monthDays } from "./monthDays.mjs";
function addMonth(inputDate, count = 1, dateOverflow = false) {
const d = date(inputDate);
const dayOfMonth = d.getDate();
if (!dateOverflow)
d.setDate(1);
d.setMonth(d.getMonth() + count);
if (!dateOverflow) {
const daysInMonth = monthDays(d);
d.setDate(daysInMonth < dayOfMonth ? daysInMonth : dayOfMonth);
}
return d;
}
export {
addMonth
};
//# sourceMappingURL=addMonth.mjs.map
{"version":3,"sources":["../src/addMonth.ts"],"sourcesContent":["import { date } from \"./date\"\nimport { monthDays } from \"./monthDays\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Returns a new date object 1/n months after the original one. Keep in mind if you\n * start with a date late in a given month you could get a date after the next\n * month.\n * @param inputDate - A date to increment by 1 or more months.\n * @param count - The quantity to add.\n * @param dateOverflow - Whether or not to allow the date to overflow to another month if the inputDate’s month is out of range of the new month.\n */\nexport function addMonth(\n inputDate: DateInput,\n count = 1,\n dateOverflow = false\n) {\n const d = date(inputDate)\n const dayOfMonth = d.getDate()\n // If overflowing is disallowed, set the date back to the first of the month\n if (!dateOverflow) d.setDate(1)\n d.setMonth(d.getMonth() + count)\n\n // If overflowing is disallowed, we need to set the date back to the proper\n // day or the last day of the month.\n if (!dateOverflow) {\n const daysInMonth = monthDays(d)\n d.setDate(daysInMonth < dayOfMonth ? daysInMonth : dayOfMonth)\n }\n return d\n}\n"],"mappings":";AAAA,SAAS,YAAY;AACrB,SAAS,iBAAiB;AAWnB,SAAS,SACd,WACA,QAAQ,GACR,eAAe,OACf;AACA,QAAM,IAAI,KAAK,SAAS;AACxB,QAAM,aAAa,EAAE,QAAQ;AAE7B,MAAI,CAAC;AAAc,MAAE,QAAQ,CAAC;AAC9B,IAAE,SAAS,EAAE,SAAS,IAAI,KAAK;AAI/B,MAAI,CAAC,cAAc;AACjB,UAAM,cAAc,UAAU,CAAC;AAC/B,MAAE,QAAQ,cAAc,aAAa,cAAc,UAAU;AAAA,EAC/D;AACA,SAAO;AACT;","names":[]}
import { DateInput } from './types.js';
/**
* Returns a new date object 1/n seconds after the original one.
* @param inputDate - A date to increment by 1 day.
*/
declare function addSecond(inputDate: DateInput, count?: number): Date;
export { addSecond };
// src/addSecond.ts
import { date } from "./date.mjs";
function addSecond(inputDate, count = 1) {
const d = date(inputDate);
d.setSeconds(d.getSeconds() + count);
return d;
}
export {
addSecond
};
//# sourceMappingURL=addSecond.mjs.map
{"version":3,"sources":["../src/addSecond.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Returns a new date object 1/n seconds after the original one.\n * @param inputDate - A date to increment by 1 day.\n */\nexport function addSecond(inputDate: DateInput, count = 1) {\n const d = date(inputDate)\n d.setSeconds(d.getSeconds() + count)\n return d\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAOd,SAAS,UAAU,WAAsB,QAAQ,GAAG;AACzD,QAAM,IAAI,KAAK,SAAS;AACxB,IAAE,WAAW,EAAE,WAAW,IAAI,KAAK;AACnC,SAAO;AACT;","names":[]}
import { DateInput } from './types.js';
/**
* Returns a new date object 1/n years after the original one. Keep in mind if
* you start with a date late in a given month you could get a date after the
* next month.
* @param inputDate - A date to increment by 1 day.
* @param count - The quantity of years add.
* @param dateOverflow - Whether or not to allow the date to overflow to another month if the inputDate’s month is out of range of the new month.
*/
declare function addYear(inputDate: DateInput, count?: number, dateOverflow?: boolean): Date;
export { addYear };
// src/addYear.ts
import { date } from "./date.mjs";
import { monthDays } from "./monthDays.mjs";
function addYear(inputDate, count = 1, dateOverflow = false) {
const d = date(inputDate);
const dayOfMonth = d.getDate();
if (!dateOverflow)
d.setDate(1);
d.setFullYear(d.getFullYear() + count);
if (!dateOverflow) {
const daysInMonth = monthDays(d);
d.setDate(daysInMonth < dayOfMonth ? daysInMonth : dayOfMonth);
}
return d;
}
export {
addYear
};
//# sourceMappingURL=addYear.mjs.map
{"version":3,"sources":["../src/addYear.ts"],"sourcesContent":["import { date } from \"./date\"\nimport { monthDays } from \"./monthDays\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Returns a new date object 1/n years after the original one. Keep in mind if\n * you start with a date late in a given month you could get a date after the\n * next month.\n * @param inputDate - A date to increment by 1 day.\n * @param count - The quantity of years add.\n * @param dateOverflow - Whether or not to allow the date to overflow to another month if the inputDate’s month is out of range of the new month.\n */\nexport function addYear(inputDate: DateInput, count = 1, dateOverflow = false) {\n const d = date(inputDate)\n const dayOfMonth = d.getDate()\n // If overflowing is disallowed, set the date back to the first of the month\n if (!dateOverflow) d.setDate(1)\n\n d.setFullYear(d.getFullYear() + count)\n\n // If overflowing is disallowed, we need to set the date back to the proper\n // day or the last day of the month.\n if (!dateOverflow) {\n const daysInMonth = monthDays(d)\n d.setDate(daysInMonth < dayOfMonth ? daysInMonth : dayOfMonth)\n }\n return d\n}\n"],"mappings":";AAAA,SAAS,YAAY;AACrB,SAAS,iBAAiB;AAWnB,SAAS,QAAQ,WAAsB,QAAQ,GAAG,eAAe,OAAO;AAC7E,QAAM,IAAI,KAAK,SAAS;AACxB,QAAM,aAAa,EAAE,QAAQ;AAE7B,MAAI,CAAC;AAAc,MAAE,QAAQ,CAAC;AAE9B,IAAE,YAAY,EAAE,YAAY,IAAI,KAAK;AAIrC,MAAI,CAAC,cAAc;AACjB,UAAM,cAAc,UAAU,CAAC;AAC/B,MAAE,QAAQ,cAAc,aAAa,cAAc,UAAU;AAAA,EAC/D;AACA,SAAO;AACT;","names":[]}
/**
* Determines the correct value for am/pm by locale and memoizes it.
* @param ampm - am or pm
* @param locale - The locale to fetch.
*/
declare function ap(ampm: "am" | "pm", locale: string): string;
export { ap };
// src/ap.ts
import { dayPeriodMap, specDate, normStr } from "./common.mjs";
function ap(ampm, locale) {
const l = dayPeriodMap.get(locale);
if (l && l[ampm])
return l[ampm];
const specimen = new Date(specDate);
specimen.setUTCHours(ampm === "am" ? 5 : 20);
const subparts = new Intl.DateTimeFormat(locale, {
timeStyle: "full",
timeZone: "UTC",
hour12: true
}).formatToParts(specimen).map(normStr);
const period = subparts.find((part) => part.type === "dayPeriod");
if (period) {
const localePeriods = l || {};
dayPeriodMap.set(
locale,
Object.assign(localePeriods, { [ampm]: period.value })
);
return period.value;
}
return ampm;
}
export {
ap
};
//# sourceMappingURL=ap.mjs.map
{"version":3,"sources":["../src/ap.ts"],"sourcesContent":["import { dayPeriodMap, specDate, normStr } from \"./common\"\n\n/**\n * Determines the correct value for am/pm by locale and memoizes it.\n * @param ampm - am or pm\n * @param locale - The locale to fetch.\n */\nexport function ap(ampm: \"am\" | \"pm\", locale: string): string {\n const l = dayPeriodMap.get(locale)\n if (l && l[ampm]) return l[ampm] as string\n const specimen = new Date(specDate)\n specimen.setUTCHours(ampm === \"am\" ? 5 : 20)\n const subparts = new Intl.DateTimeFormat(locale, {\n timeStyle: \"full\",\n timeZone: \"UTC\",\n hour12: true,\n })\n .formatToParts(specimen)\n .map(normStr)\n const period = subparts.find((part) => part.type === \"dayPeriod\")\n if (period) {\n const localePeriods: { am?: string; pm?: string } = l || {}\n dayPeriodMap.set(\n locale,\n Object.assign(localePeriods, { [ampm]: period.value })\n )\n return period.value\n }\n return ampm\n}\n"],"mappings":";AAAA,SAAS,cAAc,UAAU,eAAe;AAOzC,SAAS,GAAG,MAAmB,QAAwB;AAC5D,QAAM,IAAI,aAAa,IAAI,MAAM;AACjC,MAAI,KAAK,EAAE,IAAI;AAAG,WAAO,EAAE,IAAI;AAC/B,QAAM,WAAW,IAAI,KAAK,QAAQ;AAClC,WAAS,YAAY,SAAS,OAAO,IAAI,EAAE;AAC3C,QAAM,WAAW,IAAI,KAAK,eAAe,QAAQ;AAAA,IAC/C,WAAW;AAAA,IACX,UAAU;AAAA,IACV,QAAQ;AAAA,EACV,CAAC,EACE,cAAc,QAAQ,EACtB,IAAI,OAAO;AACd,QAAM,SAAS,SAAS,KAAK,CAAC,SAAS,KAAK,SAAS,WAAW;AAChE,MAAI,QAAQ;AACV,UAAM,gBAA8C,KAAK,CAAC;AAC1D,iBAAa;AAAA,MACX;AAAA,MACA,OAAO,OAAO,eAAe,EAAE,CAAC,IAAI,GAAG,OAAO,MAAM,CAAC;AAAA,IACvD;AACA,WAAO,OAAO;AAAA,EAChB;AACA,SAAO;AACT;","names":[]}
import { DateInput } from './types.js';
/**
* Apply a given offset to a date, returning a new date with the offset
* applied by adding or subtracting the given number of minutes.
* @param dateInput - The date to apply the offset to.
* @param offset - The offset to apply in the +-HHmm or +-HH:mm format.
*/
declare function applyOffset(dateInput: DateInput, offset?: string): Date;
export { applyOffset };
// src/applyOffset.ts
import { date } from "./date.mjs";
import { fixedLengthByOffset, offsetToMins } from "./common.mjs";
function applyOffset(dateInput, offset = "+00:00") {
const d = date(dateInput);
const token = (() => {
switch (fixedLengthByOffset(offset)) {
case 5:
return "ZZ";
case 6:
return "Z";
}
})();
const timeDiffInMins = offsetToMins(offset, token);
return new Date(d.getTime() + timeDiffInMins * 1e3 * 60);
}
export {
applyOffset
};
//# sourceMappingURL=applyOffset.mjs.map
{"version":3,"sources":["../src/applyOffset.ts"],"sourcesContent":["import { date } from \"./date\"\nimport { TimezoneToken, fixedLengthByOffset, offsetToMins } from \"./common\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Apply a given offset to a date, returning a new date with the offset\n * applied by adding or subtracting the given number of minutes.\n * @param dateInput - The date to apply the offset to.\n * @param offset - The offset to apply in the +-HHmm or +-HH:mm format.\n */\nexport function applyOffset(dateInput: DateInput, offset = \"+00:00\"): Date {\n const d = date(dateInput)\n const token = ((): TimezoneToken => {\n switch (fixedLengthByOffset(offset)) {\n case 5:\n return \"ZZ\"\n case 6:\n return \"Z\"\n }\n })()\n const timeDiffInMins = offsetToMins(offset, token)\n return new Date(d.getTime() + timeDiffInMins * 1000 * 60)\n}\n"],"mappings":";AAAA,SAAS,YAAY;AACrB,SAAwB,qBAAqB,oBAAoB;AAS1D,SAAS,YAAY,WAAsB,SAAS,UAAgB;AACzE,QAAM,IAAI,KAAK,SAAS;AACxB,QAAM,SAAS,MAAqB;AAClC,YAAQ,oBAAoB,MAAM,GAAG;AAAA,MACnC,KAAK;AACH,eAAO;AAAA,MACT,KAAK;AACH,eAAO;AAAA,IACX;AAAA,EACF,GAAG;AACH,QAAM,iBAAiB,aAAa,QAAQ,KAAK;AACjD,SAAO,IAAI,KAAK,EAAE,QAAQ,IAAI,iBAAiB,MAAO,EAAE;AAC1D;","names":[]}
// src/iso8601.ts
var iso8601Match = /^([0-9]{4})-([0-1][0-9])(?:-([0-3][0-9]))?(?:[T ]?([0-2][0-9])(?::([0-5][0-9]))?(?::([0-5][0-9]))?)?(?:\.[0-9]+)?(Z|(?:\+|\-)[0-9]{2}:?[0-9]{2})?$/;
function iso8601(date2) {
const matches = date2.match(iso8601Match);
if (matches) {
const month = Number(matches[2]);
if (month < 1 || month > 12)
return false;
if (typeof matches[3] !== void 0) {
const date3 = Number(matches[3]);
if (date3 < 1 || date3 > 31)
return false;
}
if (typeof matches[4] !== void 0) {
const hours = Number(matches[4]);
if (hours < 0 || hours > 23)
return false;
}
return true;
}
return false;
}
// src/date.ts
function normalize(date2) {
const matches = date2.match(iso8601Match);
if (matches && typeof matches[4] === "undefined") {
return date2 += "T00:00:00";
}
return date2;
}
function date(date2) {
if (!date2) {
date2 = /* @__PURE__ */ new Date();
}
if (date2 instanceof Date) {
const d = new Date(date2);
d.setMilliseconds(0);
return d;
}
date2 = date2.trim();
if (iso8601(date2)) {
return new Date(normalize(date2));
}
throw new Error(`Non ISO 8601 compliant date (${date2}).`);
}
// src/addDay.ts
function addDay(inputDate, count = 1) {
const d = date(inputDate);
d.setDate(d.getDate() + count);
return d;
}
// src/monthEnd.ts
function monthEnd(inputDate) {
const d = date(inputDate);
d.setDate(1);
d.setMonth(d.getMonth() + 1);
d.setDate(0);
return d;
}
// src/monthDays.ts
function monthDays(inputDate) {
const d = monthEnd(inputDate);
return d.getDate();
}
// src/addMonth.ts
function addMonth(inputDate, count = 1, dateOverflow = false) {
const d = date(inputDate);
const dayOfMonth = d.getDate();
if (!dateOverflow)
d.setDate(1);
d.setMonth(d.getMonth() + count);
if (!dateOverflow) {
const daysInMonth = monthDays(d);
d.setDate(daysInMonth < dayOfMonth ? daysInMonth : dayOfMonth);
}
return d;
}
// src/addYear.ts
function addYear(inputDate, count = 1, dateOverflow = false) {
const d = date(inputDate);
const dayOfMonth = d.getDate();
if (!dateOverflow)
d.setDate(1);
d.setFullYear(d.getFullYear() + count);
if (!dateOverflow) {
const daysInMonth = monthDays(d);
d.setDate(daysInMonth < dayOfMonth ? daysInMonth : dayOfMonth);
}
return d;
}
// src/addHour.ts
function addHour(inputDate, count = 1) {
const d = date(inputDate);
d.setHours(d.getHours() + count);
return d;
}
// src/addMinute.ts
function addMinute(inputDate, count = 1) {
const d = date(inputDate);
d.setMinutes(d.getMinutes() + count);
return d;
}
// src/addSecond.ts
function addSecond(inputDate, count = 1) {
const d = date(inputDate);
d.setSeconds(d.getSeconds() + count);
return d;
}
// src/common.ts
var specDate = "1999-03-04T02:05:01.000Z";
var memoParts = /* @__PURE__ */ new Map();
var clockAgnostic = [
["YYYY", { year: "numeric" }],
["YY", { year: "2-digit" }],
["MMMM", { month: "long" }],
["MMM", { month: "short" }],
["MM", { month: "2-digit" }],
["M", { month: "numeric" }],
["DD", { day: "2-digit" }],
["D", { day: "numeric" }],
["dddd", { weekday: "long" }],
["ddd", { weekday: "short" }],
["d", { weekday: "narrow" }],
["mm", { minute: "2-digit" }],
["m", { minute: "numeric" }],
["ss", { second: "2-digit" }],
["s", { second: "numeric" }],
["ZZ", { timeZoneName: "long" }],
["Z", { timeZoneName: "short" }]
];
var clock24 = [
["HH", { hour: "2-digit" }],
["H", { hour: "numeric" }]
];
var clock12 = [
["hh", { hour: "2-digit" }],
["h", { hour: "numeric" }],
["a", { dayPeriod: "narrow" }],
["A", { dayPeriod: "narrow" }]
];
var fixedLength = {
DD: 2,
HH: 2,
MM: 2,
YY: 2,
YYYY: 4,
hh: 2,
mm: 2,
ss: 2
};
function fixedLengthByOffset(offsetString) {
if (/^[+-]\d{2}:\d{2}/.test(offsetString)) {
return 6;
}
if (/^[+-]\d{4}/.test(offsetString)) {
return 5;
}
throw new Error("Invalid offset format");
}
var genitiveTokens = ["MMMM", "MMM", "dddd", "ddd"];
var tokens = /* @__PURE__ */ new Map(
/* @__PURE__ */ [...clockAgnostic, ...clock24, ...clock12].map((format2) => {
return [format2[0], format2];
})
);
var dayPeriodMap = /* @__PURE__ */ new Map();
var styles = [
"full",
"long",
"medium",
"short"
];
var two = (n) => String(n).padStart(2, "0");
var four = (n) => String(n).padStart(2, "0");
function normStr(part) {
if (part.type === "literal") {
part.value = part.value.normalize("NFKC");
}
return part;
}
function fill(inputDate, parts2, locale, genitive = false, offset2 = null) {
const partMap = createPartMap(inputDate, parts2, locale, genitive);
const d = date(inputDate);
function value({ partName, partValue, token }) {
if (partName === "literal")
return partValue;
const value2 = partMap[partName];
if (partName === "hour" && token === "H") {
return value2.replace(/^0/, "") || "0";
}
if (["mm", "ss", "MM"].includes(token) && value2.length === 1) {
return `0${value2}`;
}
if (partName === "dayPeriod") {
const p = ap(d.getUTCHours() < 12 ? "am" : "pm", locale);
return token === "A" ? p.toUpperCase() : p.toLowerCase();
}
if (partName === "timeZoneName") {
return offset2 != null ? offset2 : minsToOffset(-1 * d.getTimezoneOffset(), token);
}
return value2;
}
return parts2.map((part) => {
return {
...part,
value: value(part)
};
});
}
function createPartMap(inputDate, parts2, locale, genitive = false) {
const d = date(inputDate);
const hour12 = parts2.filter((part) => part.hour12);
const hour24 = parts2.filter((part) => !part.hour12);
const valueParts = [];
const genitiveParts = [];
function addValues(requestedParts, hour122 = false) {
const preciseLocale = `${locale}-u-hc-${hour122 ? "h12" : "h23"}`;
valueParts.push(
...new Intl.DateTimeFormat(
preciseLocale,
requestedParts.reduce(
(options, part) => {
if (part.partName === "literal")
return options;
if (genitive && genitiveTokens.includes(part.token)) {
genitiveParts.push(part);
}
return Object.assign(options, part.option);
},
{ timeZone: "UTC" }
)
).formatToParts(d).map(normStr)
);
if (genitive && genitiveParts.length) {
for (const part of genitiveParts) {
let formattedParts = [];
switch (part.token) {
case "MMMM":
formattedParts = new Intl.DateTimeFormat(preciseLocale, {
dateStyle: "long",
timeZone: "UTC"
}).formatToParts(d).map(normStr);
break;
case "MMM":
formattedParts = new Intl.DateTimeFormat(preciseLocale, {
dateStyle: "medium",
timeZone: "UTC"
}).formatToParts(d).map(normStr);
break;
}
const genitiveFormattedPart = formattedParts.find(
(p) => p.type === part.partName
);
const index = valueParts.findIndex((p) => p.type === part.partName);
if (genitiveFormattedPart && index > -1) {
valueParts[index] = genitiveFormattedPart;
}
}
}
}
if (hour12.length)
addValues(hour12, true);
if (hour24.length)
addValues(hour24);
return valueParts.reduce((map, part) => {
map[part.type] = part.value;
return map;
}, {});
}
function minsToOffset(timeDiffInMins, token = "Z") {
const hours = String(Math.floor(Math.abs(timeDiffInMins / 60))).padStart(
2,
"0"
);
const mins = String(Math.abs(timeDiffInMins % 60)).padStart(2, "0");
const sign = timeDiffInMins < 0 ? "-" : "+";
if (token === "ZZ") {
return `${sign}${hours}${mins}`;
}
return `${sign}${hours}:${mins}`;
}
function offsetToMins(offset2, token) {
validOffset(offset2, token);
const [_, sign, hours, mins] = offset2.match(
/([+-])([0-3][0-9]):?([0-6][0-9])/
);
const offsetInMins = Number(hours) * 60 + Number(mins);
return sign === "+" ? offsetInMins : -offsetInMins;
}
function validOffset(offset2, token = "Z") {
const valid = ((token2) => {
switch (token2) {
case "Z":
return /^([+-])[0-3][0-9]:[0-6][0-9]$/.test(offset2);
case "ZZ":
return /^([+-])[0-3][0-9][0-6][0-9]$/.test(offset2);
}
})(token);
if (!valid)
throw new Error(`Invalid offset: ${offset2}`);
return offset2;
}
function escapeTokens(str) {
return clockAgnostic.concat(clock24).concat(clock12).sort((a, b) => a[0].length > b[0].length ? 1 : -1).reduce((target, part) => {
return target.replace(part[0], `\\${part[0]}`);
}, str);
}
function isNumeric(part) {
return ["numeric", "2-digit"].includes(part.partValue);
}
function validate(parts2) {
let lastPart = void 0;
for (const part of parts2) {
if (part.partName === "literal" && !isNaN(parseFloat(part.partValue))) {
throw new Error(`Numbers in format (${part.partValue}).`);
}
if (lastPart && lastPart.partName !== "literal" && part.partName !== "literal") {
if (!(lastPart.token in fixedLength) && !(part.token in fixedLength) && !(isNumeric(lastPart) && part.token.toLowerCase() === "a")) {
throw new Error(
`Illegal adjacent tokens (${lastPart.token}, ${part.token})`
);
}
}
lastPart = part;
}
return parts2;
}
function getOffsetFormat(format2) {
if (typeof format2 === "string") {
return format2.includes("ZZ") ? "ZZ" : "Z";
}
return "time" in format2 && format2.time === "full" ? "Z" : "ZZ";
}
// src/ap.ts
function ap(ampm, locale) {
const l = dayPeriodMap.get(locale);
if (l && l[ampm])
return l[ampm];
const specimen = new Date(specDate);
specimen.setUTCHours(ampm === "am" ? 5 : 20);
const subparts = new Intl.DateTimeFormat(locale, {
timeStyle: "full",
timeZone: "UTC",
hour12: true
}).formatToParts(specimen).map(normStr);
const period = subparts.find((part) => part.type === "dayPeriod");
if (period) {
const localePeriods = l || {};
dayPeriodMap.set(
locale,
Object.assign(localePeriods, { [ampm]: period.value })
);
return period.value;
}
return ampm;
}
// src/applyOffset.ts
function applyOffset(dateInput, offset2 = "+00:00") {
const d = date(dateInput);
const token = (() => {
switch (fixedLengthByOffset(offset2)) {
case 5:
return "ZZ";
case 6:
return "Z";
}
})();
const timeDiffInMins = offsetToMins(offset2, token);
return new Date(d.getTime() + timeDiffInMins * 1e3 * 60);
}
// src/deviceTZ.ts
function deviceTZ() {
return Intl.DateTimeFormat().resolvedOptions().timeZone;
}
// src/offset.ts
function relativeTime(d, timeZone) {
const utcParts = new Intl.DateTimeFormat("en-US", {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
timeZone,
hourCycle: "h23"
}).formatToParts(d).map(normStr);
const parts2 = {};
utcParts.forEach((part) => {
parts2[part.type] = part.value;
});
return /* @__PURE__ */ new Date(
`${parts2.year}-${parts2.month}-${parts2.day}T${parts2.hour}:${parts2.minute}:${parts2.second}Z`
);
}
function offset(utcTime, tzA = "UTC", tzB = "device", timeZoneToken = "Z") {
var _a;
tzB = tzB === "device" ? (_a = deviceTZ()) != null ? _a : "utc" : tzB;
const d = date(utcTime);
const timeA = relativeTime(d, tzA);
const timeB = relativeTime(d, tzB);
const timeDiffInMins = (timeB.getTime() - timeA.getTime()) / 1e3 / 60;
return minsToOffset(timeDiffInMins, timeZoneToken);
}
// src/tzDate.ts
function tzDate(inputDate, tz) {
const d = date(inputDate);
return applyOffset(d, offset(d, tz));
}
// src/dayOfYear.ts
function dayOfYear(inputDate) {
const d = date(inputDate);
return Math.round(
(new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0, 0).getTime() - new Date(d.getFullYear(), 0, 0).getTime()) / 864e5
);
}
// src/dayEnd.ts
function dayEnd(inputDate) {
const d = date(inputDate);
d.setHours(23, 59, 59, 999);
return d;
}
// src/dayStart.ts
function dayStart(inputDate) {
const d = date(inputDate);
d.setHours(0, 0, 0);
return d;
}
// src/parts.ts
function parts(format2, locale) {
if (styles.includes(format2) || typeof format2 === "object") {
return styleParts(format2, locale);
}
let f = format2;
let match = 0;
const testPattern = (pattern) => {
if (!pattern[2])
pattern[2] = new RegExp(`(.)?(${pattern[0]})`, "g");
if (pattern[2].test(f)) {
let didAdd = 0;
f = f.replace(pattern[2], (_, prefix, actualMatch) => {
if (prefix === "\\")
return actualMatch;
return `${typeof prefix === "string" ? prefix : ""}{!${didAdd++ ? match : match++}!}`;
});
return !!didAdd;
}
return false;
};
function validate2(patterns) {
const parts3 = patterns.map((part) => part.partName);
const deduped = new Set(parts3);
if (parts3.length > deduped.size) {
throw new Error(`Cannot reuse format tokens.`);
}
return patterns;
}
function createPart(hour12, [token, option, exp]) {
const partName = Object.keys(option)[0];
const partValue = option[partName];
return {
option,
partName,
partValue,
token,
pattern: exp,
hour12
};
}
const found24Patterns = clockAgnostic.filter(testPattern).concat(clock24.filter(testPattern)).map(createPart.bind(null, false));
const parts2 = validate2(
found24Patterns.concat(
clock12.filter(testPattern).map(createPart.bind(null, true))
)
);
const extractIndex = /^\{!(\d+)!\}$/;
return f.split(/(\{!\d+!\})/).map((match2) => {
const hasIndex = match2.match(extractIndex);
if (hasIndex) {
return parts2[Number(hasIndex[1])];
}
return {
option: { literal: match2 },
partName: "literal",
partValue: match2,
token: match2,
pattern: new RegExp(""),
hour12: false
};
}).filter((part) => !(part.partName === "literal" && part.partValue === ""));
}
function styleParts(format2, locale) {
const options = {
timeZone: "UTC"
};
if (typeof format2 === "string") {
options.dateStyle = format2;
} else {
if ("date" in format2)
options.dateStyle = format2.date;
if ("time" in format2)
options.timeStyle = format2.time;
}
const formatter = new Intl.DateTimeFormat(locale, options);
const segments = formatter.formatToParts(new Date(specDate)).map(normStr);
const hourTypeSegments = formatter.formatToParts(/* @__PURE__ */ new Date("1999-04-05T23:05:01.000Z")).map(normStr);
const hourPart = hourTypeSegments.find((segment) => segment.type === "hour");
const hourType = hourPart && hourPart.value === "23" ? 24 : 12;
return segments.map((part) => {
const partName = part.type;
const formatPattern = guessPattern(
part.type,
part.value,
locale,
part.type === "hour" ? hourType : void 0,
options
);
if (formatPattern === void 0)
return;
const partValue = formatPattern[1][partName];
if (!partValue)
return;
if (!formatPattern[2])
formatPattern[2] = new RegExp(`${formatPattern[0]}`, "g");
return {
option: { [partName]: partValue },
partName,
partValue,
token: formatPattern[0],
pattern: formatPattern[2],
hour12: hourType === 12
};
}).filter((part) => !!part);
}
function guessPattern(partName, partValue, locale, hour, options) {
const l = partValue.length;
const n = !isNaN(Number(partValue));
let style;
switch (partName) {
case "year":
return l === 2 ? tokens.get("YY") : tokens.get("YYYY");
case "month":
if (n)
return l === 1 ? tokens.get("M") : tokens.get("MM");
style = partStyle(locale, partName, partValue);
switch (style) {
case "long":
return tokens.get("MMMM");
default:
return tokens.get("MMM");
}
case "day":
return l === 1 ? tokens.get("D") : tokens.get("DD");
case "weekday":
style = partStyle(locale, partName, partValue);
switch (style) {
case "narrow":
return tokens.get("d");
case "short":
return tokens.get("ddd");
default:
return tokens.get("dddd");
}
case "hour":
if (hour === 12)
return l === 1 ? tokens.get("h") : tokens.get("hh");
return l === 1 ? tokens.get("H") : tokens.get("HH");
case "minute":
return l === 1 ? tokens.get("m") : tokens.get("mm");
case "second":
return l === 1 ? tokens.get("s") : tokens.get("ss");
case "dayPeriod":
return /^[A-Z]+$/u.test(partValue) ? tokens.get("A") : tokens.get("a");
case "literal":
return [partValue, { literal: partValue }, new RegExp("")];
case "timeZoneName":
return options.timeStyle === "full" ? tokens.get("Z") : tokens.get("ZZ");
default:
return void 0;
}
}
function partStyle(locale, part, value) {
if (!memoParts.has(locale)) {
const date2 = new Date(specDate);
const weekdays = [3, 8, 9, 7, 6, 4, 3];
const parts2 = ["weekday", "month", "dayPeriod"];
const partStyles = ["long", "short", "narrow"];
const formats2 = {};
for (let i = 0; i < 12; i++) {
date2.setMonth(0 + i);
if (i in weekdays)
date2.setDate(weekdays[i]);
date2.setUTCHours(8 + i);
for (const style of partStyles) {
const segments = new Intl.DateTimeFormat(
locale,
parts2.reduce(
(options, part2) => Object.assign(options, { [part2]: style }),
{ hour12: true, timeZone: "UTC" }
)
).formatToParts(date2).map(normStr);
if (style === "long" || style === "short") {
const genitiveFormattedParts = new Intl.DateTimeFormat(locale, {
dateStyle: style === "short" ? "medium" : "long",
timeZone: "UTC"
}).formatToParts(date2).map(normStr);
const genitiveMonth = genitiveFormattedParts.find(
(part2) => part2.type === "month"
);
const index = segments.findIndex((part2) => part2.type === "month");
if (index > -1 && genitiveMonth)
segments[index] = genitiveMonth;
}
segments.forEach((part2) => {
if (part2.type === "literal")
return;
const type = part2.type;
formats2[type] = Object.assign(formats2[type] || {}, {
[part2.value]: style
});
});
}
}
memoParts.set(locale, formats2);
}
const formats = memoParts.get(locale);
return formats ? formats[part][value] : void 0;
}
// src/removeOffset.ts
function removeOffset(dateInput, offset2 = "+00:00") {
const positive = offset2.slice(0, 1) === "+";
return applyOffset(
dateInput,
offset2.replace(positive ? "+" : "-", positive ? "-" : "+")
);
}
// src/deviceLocale.ts
function deviceLocale() {
return Intl.DateTimeFormat().resolvedOptions().locale;
}
// src/format.ts
function format(inputDateOrOptions, format2 = "long", locale = "device", genitive = false, partFilter) {
let tz, forceOffset;
if (typeof inputDateOrOptions === "object" && !(inputDateOrOptions instanceof Date)) {
;
({
date: inputDateOrOptions,
format: format2,
locale,
genitive,
partFilter,
tz
} = inputDateOrOptions);
}
if (format2 === "ISO8601")
return date(inputDateOrOptions).toISOString();
if (tz) {
forceOffset = offset(inputDateOrOptions, "utc", tz, getOffsetFormat(format2));
}
tz != null ? tz : tz = deviceTZ();
if ((tz == null ? void 0 : tz.toLowerCase()) !== "utc") {
inputDateOrOptions = removeOffset(
inputDateOrOptions,
offset(inputDateOrOptions, tz, "utc")
);
}
if (!locale || locale === "device") {
locale = deviceLocale();
}
return fill(
inputDateOrOptions,
parts(format2, locale).filter(partFilter != null ? partFilter : () => true),
locale,
genitive,
forceOffset
).map((p) => p.value).join("");
}
// src/formatStr.ts
function formatStr(format2, locale = "en", escapeLiterals = false, filterParts = () => true) {
return parts(format2, locale).filter(filterParts).reduce(
(f, p) => f += escapeLiterals && p.partName === "literal" ? escapeTokens(p.token) : p.token,
""
).normalize("NFKC");
}
// src/fourDigitYear.ts
function fourDigitYear(value) {
const y = (/* @__PURE__ */ new Date()).getFullYear();
const currentYear = y % 100;
const century = Math.floor(y / 100);
const parsedYear = Number(value);
return (century + (parsedYear > currentYear + 20 ? -1 : 0)) * 100 + parsedYear;
}
// src/hourEnd.ts
function hourEnd(inputDate) {
const d = date(inputDate);
d.setMinutes(59, 59, 999);
return d;
}
// src/hourStart.ts
function hourStart(inputDate) {
const d = date(inputDate);
d.setMinutes(0, 0);
return d;
}
// src/minuteEnd.ts
function minuteEnd(inputDate) {
const d = date(inputDate);
d.setSeconds(59, 999);
return d;
}
// src/minuteStart.ts
function minuteStart(inputDate) {
const d = date(inputDate);
d.setSeconds(0);
return d;
}
// src/monthStart.ts
function monthStart(inputDate) {
const d = date(inputDate);
d.setDate(1);
d.setHours(0, 0, 0);
return d;
}
// src/yearDays.ts
function yearDays(inputDate) {
const d = date(inputDate);
return (new Date(d.getFullYear() + 1, 0, 0).getTime() - new Date(d.getFullYear(), 0, 0).getTime()) / 864e5;
}
// src/nearestDay.ts
function nearestDay(inputDate, search, constraint = 7) {
let increments;
let decrements;
const d = date(inputDate);
switch (constraint) {
case "month":
decrements = d.getDate();
increments = monthDays(d) - d.getDate();
break;
case "week":
decrements = d.getDay() + 1;
increments = 6 - d.getDay();
break;
case "year":
const total = yearDays(d);
const day = dayOfYear(d);
decrements = day;
increments = total - day;
break;
default:
increments = decrements = constraint;
}
for (let i = 0; i <= increments || i < decrements; i++) {
if (i <= increments) {
const next = addDay(d, i);
if (search(next))
return next;
}
if (i && i <= decrements) {
const prev = addDay(d, -i);
if (search(prev))
return prev;
}
}
return null;
}
// src/range.ts
function range(token, locale = "en", genitive = false) {
const r = (n, c) => Array(n).fill("").map((_, i) => `${c(i)}`);
if (token === "M")
return r(12, (i) => i + 1);
if (token === "MM")
return r(12, (i) => {
const m = i + 1;
return m < 10 ? `0${m}` : m;
});
if (token.startsWith("M"))
return range("MM").map(
(m) => format(`2000-${m}-05`, token, locale, genitive)
);
if (token.startsWith("d"))
return r(7, (i) => `0${i + 2}`).map(
(d) => format(`2022-10-${d}`, token, locale)
);
if (token === "a")
return [ap("am", locale).toLowerCase(), ap("pm", locale).toLowerCase()];
if (token === "A")
return [ap("am", locale).toUpperCase(), ap("pm", locale).toUpperCase()];
if (token.startsWith("Y")) {
const year = (/* @__PURE__ */ new Date()).getFullYear();
return r(120, (i) => i + 1).reduce(
(ranges, i) => {
if (i !== "120")
ranges.push(format(`${year + Number(i)}-06-06`, token, locale));
ranges.unshift(format(`${year - Number(i)}-06-06`, token, locale));
return ranges;
},
[format(`${year}-06-06`, token, locale)]
);
}
if (token.startsWith("D"))
return r(31, (i) => `${token === "DD" && i < 9 ? "0" : ""}${i + 1}`);
if (token.startsWith("H"))
return r(24, (i) => `${token === "HH" && i < 10 ? "0" : ""}${i}`);
if (token.startsWith("h"))
return r(12, (i) => `${token === "hh" && i < 9 ? "0" : ""}${i + 1}`);
if (token.startsWith("m") || token.startsWith("s"))
return r(60, (i) => `${token.length > 1 && i < 10 ? "0" : ""}${i}`);
return [];
}
// src/parse.ts
function parse(dateStrOrOptions, format2 = "ISO8601", locale = "device") {
let partFilter = () => true;
let dateStr;
let dateOverflow = "backward";
if (typeof dateStrOrOptions === "object") {
;
({
date: dateStr,
format: format2 = "ISO8601",
locale = "device",
dateOverflow = "backward",
partFilter = () => true
} = dateStrOrOptions);
} else {
dateStr = dateStrOrOptions;
}
if (!dateStr)
throw new Error("parse() requires a date string.");
const invalid = () => {
throw new Error(
`Date (${dateStr}) does not match format (${formatStr(format2, locale)})`
);
};
if (format2 === "ISO8601")
return date(dateStr);
const genitive = styles.includes(format2) || typeof format2 === "object";
const formatParts = validate(parts(format2, locale).filter(partFilter));
if (!formatParts.length)
throw new Error("parse() requires a pattern.");
let parsedParts;
try {
parsedParts = parseParts(dateStr, formatParts);
} catch {
return invalid();
}
const now = /* @__PURE__ */ new Date();
const parsed = /* @__PURE__ */ new Map([
["YYYY", now.getFullYear()],
["MM", now.getMonth() + 1],
["DD", now.getDate()],
["HH", 0],
["mm", 0],
["ss", 0]
]);
let a = null;
let offset2 = "";
parsedParts.forEach((part) => {
if (part.partName === "literal")
return;
if (part.token === part.value)
return invalid();
const v = Number(part.value);
if (parsed.has(part.token)) {
parsed.set(part.token, v);
} else if (part.token === "YY") {
parsed.set("YYYY", fourDigitYear(part.value));
} else {
const t = part.token;
if (t.startsWith("d")) {
return;
} else if (t === "D") {
parsed.set("DD", v);
} else if (t === "H" || t.startsWith("h")) {
parsed.set("HH", v);
} else if (t === "M") {
parsed.set("MM", v);
} else if (t === "a" || t === "A") {
a = part.value.toLowerCase() === ap("am", locale).toLowerCase();
} else if (t === "Z" || t === "ZZ") {
offset2 = validOffset(part.value, t);
} else {
const values = range(t, locale, genitive);
const index = values.indexOf(part.value);
if (index !== -1) {
switch (t) {
case "MMM":
case "MMMM":
parsed.set("MM", index + 1);
break;
}
}
}
}
});
let hours = parsed.get("HH") || 0;
if (a === false) {
hours += hours === 12 ? 0 : 12;
parsed.set("HH", hours === 24 ? 0 : hours);
} else if (a === true && hours === 12) {
parsed.set("HH", 0);
}
parsed.set("MM", (parsed.get("MM") || 1) - 1);
let [Y, M, D, h, m, s] = Array.from(parsed.values());
const maxDaysInMonth = monthDays(/* @__PURE__ */ new Date(`${four(Y)}-${two(M + 1)}-10`));
if (maxDaysInMonth < D && dateOverflow === "throw")
throw new Error(`Invalid date ${four(Y)}-${two(M + 1)}-${two(D)}`);
D = dateOverflow === "backward" ? Math.min(D, maxDaysInMonth) : D;
const isoString = `${four(Y)}-${two(M + 1)}-${two(D)}T${two(h)}:${two(
m
)}:${two(s)}${offset2}`;
const d = new Date(isoString);
if (isFinite(+d))
return d;
return invalid();
}
function parseParts(dateStr, formatParts) {
let i = 0;
const advance = (parts2) => [
parts2[i++],
parts2[i]
];
let pos = 0;
const parsed = [];
let n = void 0;
do {
const [current, next] = advance(formatParts);
n = next;
let len = 1;
if (current.partName === "literal") {
len = current.partValue.length;
} else if (current.partName === "timeZoneName") {
len = fixedLengthByOffset(dateStr.substring(pos));
} else if (current.token in fixedLength) {
len = fixedLength[current.token];
} else if (next) {
if (next.partName === "literal") {
len = dateStr.indexOf(next.partValue, pos) - pos;
if (len < 0)
throw new Error();
} else if (next.partName === "dayPeriod") {
for (let i2 = 1; i2 <= 4; i2++) {
if (isNaN(Number(dateStr.charAt(pos + i2)))) {
len = i2;
break;
}
}
} else {
const nextChar = dateStr.substring(pos).search(/\d/);
if (nextChar !== -1)
len = pos + nextChar;
}
} else {
len = dateStr.length;
}
parsed.push({ ...current, value: dateStr.substring(pos, pos + len) });
pos += len;
} while (n);
return parsed;
}
// src/sameDay.ts
function sameDay(inputDateA, inputDateB) {
const a = date(inputDateA);
const b = date(inputDateB);
return a.getDate() === b.getDate() && a.getMonth() === b.getMonth() && a.getFullYear() === b.getFullYear();
}
// src/sameSecond.ts
function sameSecond(inputDateA, inputDateB) {
const a = date(inputDateA);
const b = date(inputDateB);
return a.getSeconds() === b.getSeconds();
}
// src/sameMinute.ts
function sameMinute(inputDateA, inputDateB) {
const a = date(inputDateA);
const b = date(inputDateB);
return a.getMinutes() === b.getMinutes();
}
// src/sameHour.ts
function sameHour(inputDateA, inputDateB) {
const a = date(inputDateA);
const b = date(inputDateB);
return a.getHours() === b.getHours();
}
// src/sameYear.ts
function sameYear(inputDateA, inputDateB) {
const a = date(inputDateA);
const b = date(inputDateB);
return a.getFullYear() === b.getFullYear();
}
// src/weekStart.ts
function weekStart(inputDate, startOfWeekDay = 0) {
const d = date(inputDate);
let diff = startOfWeekDay - d.getDay();
if (diff > 0)
diff = diff - 7;
d.setDate(d.getDate() + diff);
d.setHours(0, 0, 0);
return d;
}
// src/weekEnd.ts
function weekEnd(inputDate, startOfWeekDay = 0) {
const d = weekStart(inputDate, startOfWeekDay);
d.setDate(d.getDate() + 6);
d.setHours(23, 59, 59);
return d;
}
// src/yearStart.ts
function yearStart(inputDate) {
const d = date(inputDate);
d.setMonth(0);
d.setDate(1);
d.setHours(0, 0, 0);
return d;
}
// src/yearEnd.ts
function yearEnd(inputDate) {
const d = date(inputDate);
d.setMonth(11);
d.setDate(31);
d.setHours(23, 59, 59, 999);
return d;
}
// src/isBefore.ts
function isBefore(inputDate, dateToCompare) {
const _date = date(inputDate);
const _dateToCompare = date(dateToCompare);
return +_date < +_dateToCompare;
}
// src/isAfter.ts
function isAfter(inputDate, dateToCompare) {
const _date = date(inputDate);
const _dateToCompare = date(dateToCompare);
return +_date > +_dateToCompare;
}
// src/isEqual.ts
function isEqual(dateLeft, dateRight) {
const _dateLeft = date(dateLeft);
const _dateRight = date(dateRight);
return +_dateLeft === +_dateRight;
}
// src/diffMilliseconds.ts
function diffMilliseconds(dateA, dateB) {
const left = date(dateA);
const right = date(dateB);
return +left - +right;
}
// src/diffRound.ts
function diffRound(value, method = "trunc") {
const r = Math[method](value);
return r == 0 ? 0 : r;
}
// src/diffSeconds.ts
function diffSeconds(dateA, dateB, roundingMethod) {
return diffRound(diffMilliseconds(dateA, dateB) / 1e3, roundingMethod);
}
// src/diffMinutes.ts
function diffMinutes(dateA, dateB, roundingMethod) {
return diffRound(diffMilliseconds(dateA, dateB) / 6e4, roundingMethod);
}
// src/diffHours.ts
function diffHours(dateA, dateB, roundingMethod) {
return diffRound(
diffMilliseconds(dateA, dateB) / 36e5,
// 1000 * 60 * 60
roundingMethod
);
}
// src/diffDays.ts
function diffDays(dateA, dateB, roundingMethod) {
return diffRound(
diffMilliseconds(dateA, dateB) / 864e5,
// hour * 24
roundingMethod
);
}
// src/diffWeeks.ts
function diffWeeks(dateA, dateB, roundingMethod) {
return diffRound(
diffMilliseconds(dateA, dateB) / 6048e5,
// day * 7
roundingMethod
);
}
// src/diffMonths.ts
function diffMonths(dateA, dateB) {
const l = date(dateA);
const r = date(dateB);
if (l < r) {
const rs = diffMonths(r, l);
return rs == 0 ? 0 : -rs;
}
let months = (l.getFullYear() - r.getFullYear()) * 12 + (l.getMonth() - r.getMonth());
const ld = l.getDate();
const rd = r.getDate();
if (ld < rd) {
const lm = monthDays(l);
if (!(lm == ld && lm < rd)) {
months--;
}
}
return months == 0 ? 0 : months;
}
// src/diffYears.ts
function diffYears(dateA, dateB) {
const r = Math.trunc(diffMonths(dateA, dateB) / 12);
return r == 0 ? 0 : r;
}
export {
addDay,
addHour,
addMinute,
addMonth,
addSecond,
addYear,
ap,
applyOffset,
date,
dayEnd,
dayOfYear,
dayStart,
diffDays,
diffHours,
diffMilliseconds,
diffMinutes,
diffMonths,
diffSeconds,
diffWeeks,
diffYears,
format,
formatStr,
fourDigitYear,
hourEnd,
hourStart,
isAfter,
isBefore,
isEqual,
iso8601,
minuteEnd,
minuteStart,
monthDays,
monthEnd,
monthStart,
nearestDay,
offset,
parse,
parseParts,
parts,
range,
removeOffset,
sameDay,
sameHour,
sameMinute,
sameSecond,
sameYear,
tzDate,
weekEnd,
weekStart,
yearDays,
yearEnd,
yearStart
};
//# sourceMappingURL=bundle.mjs.map

Sorry, the diff of this file is too big to display

import { NamedFormats, FormatPattern, FormatStyle, DateInput, Part, FilledPart, Format } from './types.js';
/**
* A date to use for determining various spec details.
*/
declare const specDate = "1999-03-04T02:05:01.000Z";
/**
* A cache of Intl tokens and their respective formats.
*/
declare const memoParts: Map<string, NamedFormats>;
/**
* Clock agnostic time format patterns.
*/
declare const clockAgnostic: FormatPattern[];
/**
* Timezone tokens.
*/
declare const timeZoneTokens: readonly ["Z", "ZZ"];
/**
* Timezone token type.
*/
type TimezoneToken = (typeof timeZoneTokens)[number];
/**
* 24 hour click format patterns.
*/
declare const clock24: FormatPattern[];
/**
* 12 hour format patterns.
*/
declare const clock12: FormatPattern[];
/**
* Tokens that have a fixed length.
*/
declare const fixedLength: {
DD: number;
HH: number;
MM: number;
YY: number;
YYYY: number;
hh: number;
mm: number;
ss: number;
};
/**
* token Z can have variable length depending on the actual value, so it's
*/
declare function fixedLengthByOffset(offsetString: string): 6 | 5;
/**
* Tokens that are genitive — in that they can have "possession" when used in
* a date phrase, "March’s 4th day" (but not in english).
*
* When computing a range for these, the range can be either genitive or not.
* The same is true for parsing dates containing these tokens.
*/
declare const genitiveTokens: string[];
/**
* A map of FormatPattern tuples to their respective token.
*/
declare const tokens: Map<string, FormatPattern>;
/**
* A map of locale’s am/pm.
*/
declare const dayPeriodMap: Map<string, {
am?: string;
pm?: string;
}>;
/**
* An array of all available date styles.
*/
declare const styles: ReadonlyArray<FormatStyle>;
/**
* Creates a leading zero string of 2 digits.
* @param n - A number.
*/
declare const two: (n: number) => string;
/**
* Creates a leading zero string of 4 digits.
* @param n - A number.
*/
declare const four: (n: number) => string;
/**
* Normalizes a given part to NFKC.
* @param part - The part to normalize.
*/
declare function normStr(part: Intl.DateTimeFormatPart): Intl.DateTimeFormatPart;
/**
* Returns the parts filled with pertinent values.
* @param inputDate - The date to fill parts for
* @param parts - An array of parts to fill
* @param locale - The locale to fill with.
* @param genitive - Whether to use genitive tokens values or not.
* @param offset - The explicit offset to fill with (ignores the date’s true offset).
*/
declare function fill(inputDate: DateInput, parts: Part[], locale: string, genitive?: boolean, offset?: string | null): FilledPart[];
/**
* Converts minutes (300) to an ISO8601 compatible offset (+0400 or +04:00).
* @param timeDiffInMins - The difference in minutes between two timezones.
* @returns
*/
declare function minsToOffset(timeDiffInMins: number, token?: string): string;
/**
* Converts an offset (-0500) to minutes (-300).
* @param offset - The offset to convert to minutes.
* @param token - The timezone token format.
*/
declare function offsetToMins(offset: string, token: TimezoneToken): number;
/**
* Validates that an offset is valid according to the format:
* [+-]HHmm or [+-]HH:mm
* @param offset - The offset to validate.
* @param token - The timezone token format.
*/
declare function validOffset(offset: string, token?: TimezoneToken): string;
/**
* Given a string of tokens, escape any characters that are tokens.
* @param str - The string to escape tokens in.
* @returns The escaped string.
*/
declare function escapeTokens(str: string): string;
/**
* Checks if a given part should have a numeric value.
* @param part - A part to check
*/
declare function isNumeric(part: Part): boolean;
/**
* Validates that an array of Parts can be parsed.
* @param parts - Parts to validate for parsing ability.
*/
declare function validate(parts: Part[]): Part[] | never;
/**
* Returns the timezone token format from a given format.
* @param format - The format to check.
* @returns The timezone token format ("Z" or "ZZ").
*/
declare function getOffsetFormat(format: Format): TimezoneToken;
export { type TimezoneToken, clock12, clock24, clockAgnostic, dayPeriodMap, escapeTokens, fill, fixedLength, fixedLengthByOffset, four, genitiveTokens, getOffsetFormat, isNumeric, memoParts, minsToOffset, normStr, offsetToMins, specDate, styles, tokens, two, validOffset, validate };
// src/common.ts
import { date } from "./date.mjs";
import { ap } from "./ap.mjs";
var specDate = "1999-03-04T02:05:01.000Z";
var memoParts = /* @__PURE__ */ new Map();
var clockAgnostic = [
["YYYY", { year: "numeric" }],
["YY", { year: "2-digit" }],
["MMMM", { month: "long" }],
["MMM", { month: "short" }],
["MM", { month: "2-digit" }],
["M", { month: "numeric" }],
["DD", { day: "2-digit" }],
["D", { day: "numeric" }],
["dddd", { weekday: "long" }],
["ddd", { weekday: "short" }],
["d", { weekday: "narrow" }],
["mm", { minute: "2-digit" }],
["m", { minute: "numeric" }],
["ss", { second: "2-digit" }],
["s", { second: "numeric" }],
["ZZ", { timeZoneName: "long" }],
["Z", { timeZoneName: "short" }]
];
var clock24 = [
["HH", { hour: "2-digit" }],
["H", { hour: "numeric" }]
];
var clock12 = [
["hh", { hour: "2-digit" }],
["h", { hour: "numeric" }],
["a", { dayPeriod: "narrow" }],
["A", { dayPeriod: "narrow" }]
];
var fixedLength = {
DD: 2,
HH: 2,
MM: 2,
YY: 2,
YYYY: 4,
hh: 2,
mm: 2,
ss: 2
};
function fixedLengthByOffset(offsetString) {
if (/^[+-]\d{2}:\d{2}/.test(offsetString)) {
return 6;
}
if (/^[+-]\d{4}/.test(offsetString)) {
return 5;
}
throw new Error("Invalid offset format");
}
var genitiveTokens = ["MMMM", "MMM", "dddd", "ddd"];
var tokens = /* @__PURE__ */ new Map(
/* @__PURE__ */ [...clockAgnostic, ...clock24, ...clock12].map((format) => {
return [format[0], format];
})
);
var dayPeriodMap = /* @__PURE__ */ new Map();
var styles = [
"full",
"long",
"medium",
"short"
];
var two = (n) => String(n).padStart(2, "0");
var four = (n) => String(n).padStart(2, "0");
function normStr(part) {
if (part.type === "literal") {
part.value = part.value.normalize("NFKC");
}
return part;
}
function fill(inputDate, parts, locale, genitive = false, offset = null) {
const partMap = createPartMap(inputDate, parts, locale, genitive);
const d = date(inputDate);
function value({ partName, partValue, token }) {
if (partName === "literal")
return partValue;
const value2 = partMap[partName];
if (partName === "hour" && token === "H") {
return value2.replace(/^0/, "") || "0";
}
if (["mm", "ss", "MM"].includes(token) && value2.length === 1) {
return `0${value2}`;
}
if (partName === "dayPeriod") {
const p = ap(d.getUTCHours() < 12 ? "am" : "pm", locale);
return token === "A" ? p.toUpperCase() : p.toLowerCase();
}
if (partName === "timeZoneName") {
return offset != null ? offset : minsToOffset(-1 * d.getTimezoneOffset(), token);
}
return value2;
}
return parts.map((part) => {
return {
...part,
value: value(part)
};
});
}
function createPartMap(inputDate, parts, locale, genitive = false) {
const d = date(inputDate);
const hour12 = parts.filter((part) => part.hour12);
const hour24 = parts.filter((part) => !part.hour12);
const valueParts = [];
const genitiveParts = [];
function addValues(requestedParts, hour122 = false) {
const preciseLocale = `${locale}-u-hc-${hour122 ? "h12" : "h23"}`;
valueParts.push(
...new Intl.DateTimeFormat(
preciseLocale,
requestedParts.reduce(
(options, part) => {
if (part.partName === "literal")
return options;
if (genitive && genitiveTokens.includes(part.token)) {
genitiveParts.push(part);
}
return Object.assign(options, part.option);
},
{ timeZone: "UTC" }
)
).formatToParts(d).map(normStr)
);
if (genitive && genitiveParts.length) {
for (const part of genitiveParts) {
let formattedParts = [];
switch (part.token) {
case "MMMM":
formattedParts = new Intl.DateTimeFormat(preciseLocale, {
dateStyle: "long",
timeZone: "UTC"
}).formatToParts(d).map(normStr);
break;
case "MMM":
formattedParts = new Intl.DateTimeFormat(preciseLocale, {
dateStyle: "medium",
timeZone: "UTC"
}).formatToParts(d).map(normStr);
break;
}
const genitiveFormattedPart = formattedParts.find(
(p) => p.type === part.partName
);
const index = valueParts.findIndex((p) => p.type === part.partName);
if (genitiveFormattedPart && index > -1) {
valueParts[index] = genitiveFormattedPart;
}
}
}
}
if (hour12.length)
addValues(hour12, true);
if (hour24.length)
addValues(hour24);
return valueParts.reduce((map, part) => {
map[part.type] = part.value;
return map;
}, {});
}
function minsToOffset(timeDiffInMins, token = "Z") {
const hours = String(Math.floor(Math.abs(timeDiffInMins / 60))).padStart(
2,
"0"
);
const mins = String(Math.abs(timeDiffInMins % 60)).padStart(2, "0");
const sign = timeDiffInMins < 0 ? "-" : "+";
if (token === "ZZ") {
return `${sign}${hours}${mins}`;
}
return `${sign}${hours}:${mins}`;
}
function offsetToMins(offset, token) {
validOffset(offset, token);
const [_, sign, hours, mins] = offset.match(
/([+-])([0-3][0-9]):?([0-6][0-9])/
);
const offsetInMins = Number(hours) * 60 + Number(mins);
return sign === "+" ? offsetInMins : -offsetInMins;
}
function validOffset(offset, token = "Z") {
const valid = ((token2) => {
switch (token2) {
case "Z":
return /^([+-])[0-3][0-9]:[0-6][0-9]$/.test(offset);
case "ZZ":
return /^([+-])[0-3][0-9][0-6][0-9]$/.test(offset);
}
})(token);
if (!valid)
throw new Error(`Invalid offset: ${offset}`);
return offset;
}
function escapeTokens(str) {
return clockAgnostic.concat(clock24).concat(clock12).sort((a, b) => a[0].length > b[0].length ? 1 : -1).reduce((target, part) => {
return target.replace(part[0], `\\${part[0]}`);
}, str);
}
function isNumeric(part) {
return ["numeric", "2-digit"].includes(part.partValue);
}
function validate(parts) {
let lastPart = void 0;
for (const part of parts) {
if (part.partName === "literal" && !isNaN(parseFloat(part.partValue))) {
throw new Error(`Numbers in format (${part.partValue}).`);
}
if (lastPart && lastPart.partName !== "literal" && part.partName !== "literal") {
if (!(lastPart.token in fixedLength) && !(part.token in fixedLength) && !(isNumeric(lastPart) && part.token.toLowerCase() === "a")) {
throw new Error(
`Illegal adjacent tokens (${lastPart.token}, ${part.token})`
);
}
}
lastPart = part;
}
return parts;
}
function getOffsetFormat(format) {
if (typeof format === "string") {
return format.includes("ZZ") ? "ZZ" : "Z";
}
return "time" in format && format.time === "full" ? "Z" : "ZZ";
}
export {
clock12,
clock24,
clockAgnostic,
dayPeriodMap,
escapeTokens,
fill,
fixedLength,
fixedLengthByOffset,
four,
genitiveTokens,
getOffsetFormat,
isNumeric,
memoParts,
minsToOffset,
normStr,
offsetToMins,
specDate,
styles,
tokens,
two,
validOffset,
validate
};
//# sourceMappingURL=common.mjs.map
{"version":3,"sources":["../src/common.ts"],"sourcesContent":["import { date } from \"./date\"\nimport { ap } from \"./ap\"\nimport type {\n DateInput,\n NamedFormats,\n FormatPattern,\n FormatStyle,\n Part,\n FilledPart,\n Format,\n} from \"./types\"\n\n/**\n * A date to use for determining various spec details.\n */\nexport const specDate = \"1999-03-04T02:05:01.000Z\"\n\n/**\n * A cache of Intl tokens and their respective formats.\n */\nexport const memoParts: Map<string, NamedFormats> = new Map()\n\n/**\n * Clock agnostic time format patterns.\n */\nexport const clockAgnostic: FormatPattern[] = [\n [\"YYYY\", { year: \"numeric\" }],\n [\"YY\", { year: \"2-digit\" }],\n [\"MMMM\", { month: \"long\" }],\n [\"MMM\", { month: \"short\" }],\n [\"MM\", { month: \"2-digit\" }],\n [\"M\", { month: \"numeric\" }],\n [\"DD\", { day: \"2-digit\" }],\n [\"D\", { day: \"numeric\" }],\n [\"dddd\", { weekday: \"long\" }],\n [\"ddd\", { weekday: \"short\" }],\n [\"d\", { weekday: \"narrow\" }],\n [\"mm\", { minute: \"2-digit\" }],\n [\"m\", { minute: \"numeric\" }],\n [\"ss\", { second: \"2-digit\" }],\n [\"s\", { second: \"numeric\" }],\n [\"ZZ\", { timeZoneName: \"long\" }],\n [\"Z\", { timeZoneName: \"short\" }],\n]\n\n/**\n * Timezone tokens.\n */\nconst timeZoneTokens = [\"Z\", \"ZZ\"] as const\n\n/**\n * Timezone token type.\n */\nexport type TimezoneToken = (typeof timeZoneTokens)[number]\n\n/**\n * 24 hour click format patterns.\n */\nexport const clock24: FormatPattern[] = [\n [\"HH\", { hour: \"2-digit\" }],\n [\"H\", { hour: \"numeric\" }],\n]\n\n/**\n * 12 hour format patterns.\n */\nexport const clock12: FormatPattern[] = [\n [\"hh\", { hour: \"2-digit\" }],\n [\"h\", { hour: \"numeric\" }],\n [\"a\", { dayPeriod: \"narrow\" }],\n [\"A\", { dayPeriod: \"narrow\" }],\n]\n\n/**\n * Tokens that have a fixed length.\n */\nexport const fixedLength = {\n DD: 2,\n HH: 2,\n MM: 2,\n YY: 2,\n YYYY: 4,\n hh: 2,\n mm: 2,\n ss: 2,\n}\n\n/**\n * token Z can have variable length depending on the actual value, so it's\n */\nexport function fixedLengthByOffset(offsetString: string): 6 | 5 {\n // starts with [+-]xx:xx\n if (/^[+-]\\d{2}:\\d{2}/.test(offsetString)) {\n return 6\n }\n\n // starts with [+-]xxxx\n if (/^[+-]\\d{4}/.test(offsetString)) {\n return 5\n }\n\n throw new Error(\"Invalid offset format\")\n}\n\n/**\n * Tokens that are genitive — in that they can have \"possession\" when used in\n * a date phrase, \"March’s 4th day\" (but not in english).\n *\n * When computing a range for these, the range can be either genitive or not.\n * The same is true for parsing dates containing these tokens.\n */\nexport const genitiveTokens = [\"MMMM\", \"MMM\", \"dddd\", \"ddd\"]\n\n/**\n * A map of FormatPattern tuples to their respective token.\n */\nexport const tokens = /* @__PURE__ */ new Map(\n /* @__PURE__ */ [...clockAgnostic, ...clock24, ...clock12].map((format) => {\n return [format[0], format]\n })\n)\n\n/**\n * A map of locale’s am/pm.\n */\nexport const dayPeriodMap: Map<string, { am?: string; pm?: string }> = new Map()\n\n/**\n * An array of all available date styles.\n */\nexport const styles: ReadonlyArray<FormatStyle> = [\n \"full\",\n \"long\",\n \"medium\",\n \"short\",\n]\n\n/**\n * Creates a leading zero string of 2 digits.\n * @param n - A number.\n */\nexport const two = (n: number) => String(n).padStart(2, \"0\")\n/**\n * Creates a leading zero string of 4 digits.\n * @param n - A number.\n */\nexport const four = (n: number) => String(n).padStart(2, \"0\")\n\n/**\n * Normalizes a given part to NFKC.\n * @param part - The part to normalize.\n */\nexport function normStr(\n part: Intl.DateTimeFormatPart\n): Intl.DateTimeFormatPart {\n if (part.type === \"literal\") {\n part.value = part.value.normalize(\"NFKC\")\n }\n return part\n}\n\n/**\n * Returns the parts filled with pertinent values.\n * @param inputDate - The date to fill parts for\n * @param parts - An array of parts to fill\n * @param locale - The locale to fill with.\n * @param genitive - Whether to use genitive tokens values or not.\n * @param offset - The explicit offset to fill with (ignores the date’s true offset).\n */\nexport function fill(\n inputDate: DateInput,\n parts: Part[],\n locale: string,\n genitive = false,\n offset: string | null = null\n): FilledPart[] {\n const partMap = createPartMap(inputDate, parts, locale, genitive)\n const d = date(inputDate)\n\n /**\n * Not all values get returned \"properly\" as our tokens would suggest. For\n * example, at times Intl returns leading zeros when it shouldn't. This fn\n * is used to clean up those irregular values.\n * @param param - Part\n */\n function value({ partName, partValue, token }: Part) {\n if (partName === \"literal\") return partValue\n const value = partMap[partName]\n if (partName === \"hour\" && token === \"H\") {\n return value.replace(/^0/, \"\") || \"0\"\n }\n if ([\"mm\", \"ss\", \"MM\"].includes(token) && value.length === 1) {\n // Some tokens are supposed to have leading zeros, but Intl doesn't\n // always return them, depending on the locale and the format.\n return `0${value}`\n }\n if (partName === \"dayPeriod\") {\n const p = ap(d.getUTCHours() < 12 ? \"am\" : \"pm\", locale)\n return token === \"A\" ? p.toUpperCase() : p.toLowerCase()\n }\n if (partName === \"timeZoneName\") {\n return offset ?? minsToOffset(-1 * d.getTimezoneOffset(), token)\n }\n return value\n }\n\n return parts.map((part): FilledPart => {\n return {\n ...part,\n value: value(part),\n }\n })\n}\n\n/**\n * Creates a map of part names to their respective values.\n * @param inputDate - The date to format\n * @param parts - The individual parts the need to be formatted.\n * @param locale - The locale to format the parts with.\n * @param genitive - Whether to use genitive tokens values or not.\n */\nfunction createPartMap(\n inputDate: DateInput,\n parts: Part[],\n locale: string,\n genitive = false\n): Record<keyof Intl.DateTimeFormatPartTypesRegistry, string> {\n const d = date(inputDate)\n const hour12 = parts.filter((part) => part.hour12)\n const hour24 = parts.filter((part) => !part.hour12)\n const valueParts: Intl.DateTimeFormatPart[] = []\n const genitiveParts: Part[] = []\n\n function addValues(requestedParts: Part[], hour12 = false) {\n const preciseLocale = `${locale}-u-hc-${hour12 ? \"h12\" : \"h23\"}`\n valueParts.push(\n ...new Intl.DateTimeFormat(\n preciseLocale,\n requestedParts.reduce(\n (options, part) => {\n if (part.partName === \"literal\") return options\n // Side effect! Genitive parts get shoved into a separate array.\n if (genitive && genitiveTokens.includes(part.token)) {\n genitiveParts.push(part)\n }\n return Object.assign(options, part.option)\n },\n { timeZone: \"UTC\" } as Intl.DateTimeFormatOptions\n )\n )\n .formatToParts(d)\n .map(normStr)\n )\n if (genitive && genitiveParts.length) {\n for (const part of genitiveParts) {\n let formattedParts: Intl.DateTimeFormatPart[] = []\n switch (part.token) {\n case \"MMMM\":\n formattedParts = new Intl.DateTimeFormat(preciseLocale, {\n dateStyle: \"long\",\n timeZone: \"UTC\",\n })\n .formatToParts(d)\n .map(normStr)\n break\n case \"MMM\":\n formattedParts = new Intl.DateTimeFormat(preciseLocale, {\n dateStyle: \"medium\",\n timeZone: \"UTC\",\n })\n .formatToParts(d)\n .map(normStr)\n break\n }\n const genitiveFormattedPart = formattedParts.find(\n (p) => p.type === part.partName\n )\n const index = valueParts.findIndex((p) => p.type === part.partName)\n if (genitiveFormattedPart && index > -1) {\n valueParts[index] = genitiveFormattedPart\n }\n }\n }\n }\n\n if (hour12.length) addValues(hour12, true)\n if (hour24.length) addValues(hour24)\n\n return valueParts.reduce((map, part) => {\n map[part.type] = part.value\n return map\n }, {} as Record<keyof Intl.DateTimeFormatPartTypesRegistry, string>)\n}\n\n/**\n * Converts minutes (300) to an ISO8601 compatible offset (+0400 or +04:00).\n * @param timeDiffInMins - The difference in minutes between two timezones.\n * @returns\n */\nexport function minsToOffset(\n timeDiffInMins: number,\n token: string = \"Z\"\n): string {\n const hours = String(Math.floor(Math.abs(timeDiffInMins / 60))).padStart(\n 2,\n \"0\"\n )\n const mins = String(Math.abs(timeDiffInMins % 60)).padStart(2, \"0\")\n const sign = timeDiffInMins < 0 ? \"-\" : \"+\"\n\n if (token === \"ZZ\") {\n return `${sign}${hours}${mins}`\n }\n\n return `${sign}${hours}:${mins}`\n}\n\n/**\n * Converts an offset (-0500) to minutes (-300).\n * @param offset - The offset to convert to minutes.\n * @param token - The timezone token format.\n */\nexport function offsetToMins(offset: string, token: TimezoneToken): number {\n validOffset(offset, token)\n const [_, sign, hours, mins] = offset.match(\n /([+-])([0-3][0-9]):?([0-6][0-9])/\n )!\n const offsetInMins = Number(hours) * 60 + Number(mins)\n return sign === \"+\" ? offsetInMins : -offsetInMins\n}\n\n/**\n * Validates that an offset is valid according to the format:\n * [+-]HHmm or [+-]HH:mm\n * @param offset - The offset to validate.\n * @param token - The timezone token format.\n */\nexport function validOffset(offset: string, token: TimezoneToken = \"Z\") {\n const valid = ((token: TimezoneToken): boolean => {\n switch (token) {\n case \"Z\":\n return /^([+-])[0-3][0-9]:[0-6][0-9]$/.test(offset)\n case \"ZZ\":\n return /^([+-])[0-3][0-9][0-6][0-9]$/.test(offset)\n }\n })(token)\n\n if (!valid) throw new Error(`Invalid offset: ${offset}`)\n return offset\n}\n\n/**\n * Given a string of tokens, escape any characters that are tokens.\n * @param str - The string to escape tokens in.\n * @returns The escaped string.\n */\nexport function escapeTokens(str: string): string {\n return clockAgnostic\n .concat(clock24)\n .concat(clock12)\n .sort((a, b) => (a[0].length > b[0].length ? 1 : -1))\n .reduce((target, part) => {\n return target.replace(part[0], `\\\\${part[0]}`)\n }, str)\n}\n\n/**\n * Checks if a given part should have a numeric value.\n * @param part - A part to check\n */\nexport function isNumeric(part: Part) {\n return [\"numeric\", \"2-digit\"].includes(part.partValue)\n}\n\n/**\n * Validates that an array of Parts can be parsed.\n * @param parts - Parts to validate for parsing ability.\n */\nexport function validate(parts: Part[]): Part[] | never {\n let lastPart: Part | undefined = undefined\n for (const part of parts) {\n if (part.partName === \"literal\" && !isNaN(parseFloat(part.partValue))) {\n throw new Error(`Numbers in format (${part.partValue}).`)\n }\n if (\n lastPart &&\n lastPart.partName !== \"literal\" &&\n part.partName !== \"literal\"\n ) {\n if (\n !(lastPart.token in fixedLength) &&\n !(part.token in fixedLength) &&\n !(isNumeric(lastPart) && part.token.toLowerCase() === \"a\")\n ) {\n throw new Error(\n `Illegal adjacent tokens (${lastPart.token}, ${part.token})`\n )\n }\n }\n lastPart = part\n }\n return parts\n}\n\n/**\n * Returns the timezone token format from a given format.\n * @param format - The format to check.\n * @returns The timezone token format (\"Z\" or \"ZZ\").\n */\nexport function getOffsetFormat(format: Format): TimezoneToken {\n if (typeof format === \"string\") {\n return format.includes(\"ZZ\") ? \"ZZ\" : \"Z\"\n }\n return \"time\" in format && format.time === \"full\" ? \"Z\" : \"ZZ\"\n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SAAS,CAAC,GAAG;AACrE,YAAM,IAAI,MAAM,sBAAsB,KAAK,SAAS,IAAI;AAAA,IAC1D;AACA,QACE,YACA,SAAS,aAAa,aACtB,KAAK,aAAa,WAClB;AACA,UACE,EAAE,SAAS,SAAS,gBACpB,EAAE,KAAK,SAAS,gBAChB,EAAE,UAAU,QAAQ,KAAK,KAAK,MAAM,YAAY,MAAM,MACtD;AACA,cAAM,IAAI;AAAA,UACR,4BAA4B,SAAS,KAAK,KAAK,KAAK,KAAK;AAAA,QAC3D;AAAA,MACF;AAAA,IACF;AACA,eAAW;AAAA,EACb;AACA,SAAO;AACT;AAOO,SAAS,gBAAgB,QAA+B;AAC7D,MAAI,OAAO,WAAW,UAAU;AAC9B,WAAO,OAAO,SAAS,IAAI,IAAI,OAAO;AAAA,EACxC;AACA,SAAO,UAAU,UAAU,OAAO,SAAS,SAAS,MAAM;AAC5D;","names":["value","hour12","token"]}
import { DateInput } from './types.js';
/**
* A date to parse.
* @param date - A Date object or an ISO 8601 date.
*/
declare function date(date?: DateInput): Date;
export { date };
// src/date.ts
import { iso8601, iso8601Match } from "./iso8601.mjs";
function normalize(date2) {
const matches = date2.match(iso8601Match);
if (matches && typeof matches[4] === "undefined") {
return date2 += "T00:00:00";
}
return date2;
}
function date(date2) {
if (!date2) {
date2 = /* @__PURE__ */ new Date();
}
if (date2 instanceof Date) {
const d = new Date(date2);
d.setMilliseconds(0);
return d;
}
date2 = date2.trim();
if (iso8601(date2)) {
return new Date(normalize(date2));
}
throw new Error(`Non ISO 8601 compliant date (${date2}).`);
}
export {
date
};
//# sourceMappingURL=date.mjs.map
{"version":3,"sources":["../src/date.ts"],"sourcesContent":["import { iso8601, iso8601Match } from \"./iso8601\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Normalizes a \"short\" date like 2012-01-01 to 2012-01-01T00:00:00 to prevent\n * automatic coercion to UTC.\n * @param date - A string representation of the date.\n */\nfunction normalize(date: string) {\n const matches = date.match(iso8601Match)\n if (matches && typeof matches[4] === \"undefined\") {\n return (date += \"T00:00:00\")\n }\n return date\n}\n\n/**\n * A date to parse.\n * @param date - A Date object or an ISO 8601 date.\n */\nexport function date(date?: DateInput): Date {\n if (!date) {\n date = new Date()\n }\n if (date instanceof Date) {\n const d = new Date(date)\n d.setMilliseconds(0)\n return d\n }\n date = date.trim()\n if (iso8601(date)) {\n return new Date(normalize(date))\n }\n throw new Error(`Non ISO 8601 compliant date (${date}).`)\n}\n"],"mappings":";AAAA,SAAS,SAAS,oBAAoB;AAQtC,SAAS,UAAUA,OAAc;AAC/B,QAAM,UAAUA,MAAK,MAAM,YAAY;AACvC,MAAI,WAAW,OAAO,QAAQ,CAAC,MAAM,aAAa;AAChD,WAAQA,SAAQ;AAAA,EAClB;AACA,SAAOA;AACT;AAMO,SAAS,KAAKA,OAAwB;AAC3C,MAAI,CAACA,OAAM;AACT,IAAAA,QAAO,oBAAI,KAAK;AAAA,EAClB;AACA,MAAIA,iBAAgB,MAAM;AACxB,UAAM,IAAI,IAAI,KAAKA,KAAI;AACvB,MAAE,gBAAgB,CAAC;AACnB,WAAO;AAAA,EACT;AACA,EAAAA,QAAOA,MAAK,KAAK;AACjB,MAAI,QAAQA,KAAI,GAAG;AACjB,WAAO,IAAI,KAAK,UAAUA,KAAI,CAAC;AAAA,EACjC;AACA,QAAM,IAAI,MAAM,gCAAgCA,KAAI,IAAI;AAC1D;","names":["date"]}
import { DateInput } from './types.js';
/**
* Returns a Date object for end of the given day.
* @param inputDate - A string or Date object
*/
declare function dayEnd(inputDate: DateInput): Date;
export { dayEnd };
// src/dayEnd.ts
import { date } from "./date.mjs";
function dayEnd(inputDate) {
const d = date(inputDate);
d.setHours(23, 59, 59, 999);
return d;
}
export {
dayEnd
};
//# sourceMappingURL=dayEnd.mjs.map
{"version":3,"sources":["../src/dayEnd.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Returns a Date object for end of the given day.\n * @param inputDate - A string or Date object\n */\nexport function dayEnd(inputDate: DateInput): Date {\n const d = date(inputDate)\n d.setHours(23, 59, 59, 999)\n return d\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAOd,SAAS,OAAO,WAA4B;AACjD,QAAM,IAAI,KAAK,SAAS;AACxB,IAAE,SAAS,IAAI,IAAI,IAAI,GAAG;AAC1B,SAAO;AACT;","names":[]}
import { DateInput } from './types.js';
/**
* Gets the what day of the year a given date is. For example, August 1st is
* the 213th day of the year on non- years and 214th on leap years.
* @param inputDate - The input date.
*/
declare function dayOfYear(inputDate: DateInput): number;
export { dayOfYear };
// src/dayOfYear.ts
import { date } from "./date.mjs";
function dayOfYear(inputDate) {
const d = date(inputDate);
return Math.round(
(new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0, 0).getTime() - new Date(d.getFullYear(), 0, 0).getTime()) / 864e5
);
}
export {
dayOfYear
};
//# sourceMappingURL=dayOfYear.mjs.map
{"version":3,"sources":["../src/dayOfYear.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Gets the what day of the year a given date is. For example, August 1st is\n * the 213th day of the year on non- years and 214th on leap years.\n * @param inputDate - The input date.\n */\nexport function dayOfYear(inputDate: DateInput): number {\n const d = date(inputDate)\n return Math.round(\n (new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0, 0).getTime() -\n new Date(d.getFullYear(), 0, 0).getTime()) /\n 86400000\n )\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAQd,SAAS,UAAU,WAA8B;AACtD,QAAM,IAAI,KAAK,SAAS;AACxB,SAAO,KAAK;AAAA,KACT,IAAI,KAAK,EAAE,YAAY,GAAG,EAAE,SAAS,GAAG,EAAE,QAAQ,GAAG,GAAG,CAAC,EAAE,QAAQ,IAClE,IAAI,KAAK,EAAE,YAAY,GAAG,GAAG,CAAC,EAAE,QAAQ,KACxC;AAAA,EACJ;AACF;","names":[]}
import { DateInput } from './types.js';
/**
* Returns a Date object for start of the given day.
* @param inputDate - A string or Date object
*/
declare function dayStart(inputDate: DateInput): Date;
export { dayStart };
// src/dayStart.ts
import { date } from "./date.mjs";
function dayStart(inputDate) {
const d = date(inputDate);
d.setHours(0, 0, 0);
return d;
}
export {
dayStart
};
//# sourceMappingURL=dayStart.mjs.map
{"version":3,"sources":["../src/dayStart.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Returns a Date object for start of the given day.\n * @param inputDate - A string or Date object\n */\nexport function dayStart(inputDate: DateInput): Date {\n const d = date(inputDate)\n d.setHours(0, 0, 0)\n return d\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAOd,SAAS,SAAS,WAA4B;AACnD,QAAM,IAAI,KAAK,SAAS;AACxB,IAAE,SAAS,GAAG,GAAG,CAAC;AAClB,SAAO;AACT;","names":[]}
/**
* Returns the device's locale. This is a simple proxy of the
* `Intl.DateTimeFormat().resolvedOptions().locale` call.
*/
declare function deviceLocale(): string;
export { deviceLocale };
// src/deviceLocale.ts
function deviceLocale() {
return Intl.DateTimeFormat().resolvedOptions().locale;
}
export {
deviceLocale
};
//# sourceMappingURL=deviceLocale.mjs.map
{"version":3,"sources":["../src/deviceLocale.ts"],"sourcesContent":["/**\n * Returns the device's locale. This is a simple proxy of the\n * `Intl.DateTimeFormat().resolvedOptions().locale` call.\n */\nexport function deviceLocale() {\n return Intl.DateTimeFormat().resolvedOptions().locale\n}\n"],"mappings":";AAIO,SAAS,eAAe;AAC7B,SAAO,KAAK,eAAe,EAAE,gBAAgB,EAAE;AACjD;","names":[]}
/**
* Get the timezone of the device.
*
* * Note: If the environment variable TZ is not set, it will return undefined.
*/
declare function deviceTZ(): string | undefined;
export { deviceTZ };
// src/deviceTZ.ts
function deviceTZ() {
return Intl.DateTimeFormat().resolvedOptions().timeZone;
}
export {
deviceTZ
};
//# sourceMappingURL=deviceTZ.mjs.map
{"version":3,"sources":["../src/deviceTZ.ts"],"sourcesContent":["/**\n * Get the timezone of the device.\n *\n * * Note: If the environment variable TZ is not set, it will return undefined.\n */\nexport function deviceTZ(): string | undefined {\n return Intl.DateTimeFormat().resolvedOptions().timeZone as string | undefined\n}\n"],"mappings":";AAKO,SAAS,WAA+B;AAC7C,SAAO,KAAK,eAAe,EAAE,gBAAgB,EAAE;AACjD;","names":[]}
import { DateInput } from './types.js';
import { DiffRoundingMethod } from './diffRound.js';
/**
* Returns the difference between 2 dates in days.
* @param dateA A date to compare with the right date
* @param dateB A date to compare with the left date
* @param roundingMethod the rounding method to use, default: trunc
*/
declare function diffDays(dateA: DateInput, dateB: DateInput, roundingMethod?: DiffRoundingMethod): number;
export { diffDays };
// src/diffDays.ts
import { diffMilliseconds } from "./diffMilliseconds.mjs";
import { diffRound } from "./diffRound.mjs";
function diffDays(dateA, dateB, roundingMethod) {
return diffRound(
diffMilliseconds(dateA, dateB) / 864e5,
// hour * 24
roundingMethod
);
}
export {
diffDays
};
//# sourceMappingURL=diffDays.mjs.map
{"version":3,"sources":["../src/diffDays.ts"],"sourcesContent":["import { diffMilliseconds } from \"./diffMilliseconds\"\nimport { DateInput } from \"./types\"\nimport { diffRound, type DiffRoundingMethod } from \"./diffRound\"\n\n/**\n * Returns the difference between 2 dates in days.\n * @param dateA A date to compare with the right date\n * @param dateB A date to compare with the left date\n * @param roundingMethod the rounding method to use, default: trunc\n */\nexport function diffDays(\n dateA: DateInput,\n dateB: DateInput,\n roundingMethod?: DiffRoundingMethod\n) {\n return diffRound(\n diffMilliseconds(dateA, dateB) / 86_400_000, // hour * 24\n roundingMethod\n )\n}\n"],"mappings":";AAAA,SAAS,wBAAwB;AAEjC,SAAS,iBAA0C;AAQ5C,SAAS,SACd,OACA,OACA,gBACA;AACA,SAAO;AAAA,IACL,iBAAiB,OAAO,KAAK,IAAI;AAAA;AAAA,IACjC;AAAA,EACF;AACF;","names":[]}
import { DiffRoundingMethod } from './diffRound.js';
import { DateInput } from './types.js';
/**
* Returns the difference between 2 dates in hours.
* @param dateA A date to compare with the right date
* @param dateB A date to compare with the left date
* @param roundingMethod the rounding method to use, default: trunc
*/
declare function diffHours(dateA: DateInput, dateB: DateInput, roundingMethod?: DiffRoundingMethod): number;
export { diffHours };
// src/diffHours.ts
import { diffMilliseconds } from "./diffMilliseconds.mjs";
import { diffRound } from "./diffRound.mjs";
function diffHours(dateA, dateB, roundingMethod) {
return diffRound(
diffMilliseconds(dateA, dateB) / 36e5,
// 1000 * 60 * 60
roundingMethod
);
}
export {
diffHours
};
//# sourceMappingURL=diffHours.mjs.map
{"version":3,"sources":["../src/diffHours.ts"],"sourcesContent":["import { diffMilliseconds } from \"./diffMilliseconds\"\nimport { diffRound, type DiffRoundingMethod } from \"./diffRound\"\nimport { DateInput } from \"./types\"\n\n/**\n * Returns the difference between 2 dates in hours.\n * @param dateA A date to compare with the right date\n * @param dateB A date to compare with the left date\n * @param roundingMethod the rounding method to use, default: trunc\n */\nexport function diffHours(\n dateA: DateInput,\n dateB: DateInput,\n roundingMethod?: DiffRoundingMethod\n) {\n return diffRound(\n diffMilliseconds(dateA, dateB) / 3_600_000, // 1000 * 60 * 60\n roundingMethod\n )\n}\n"],"mappings":";AAAA,SAAS,wBAAwB;AACjC,SAAS,iBAA0C;AAS5C,SAAS,UACd,OACA,OACA,gBACA;AACA,SAAO;AAAA,IACL,iBAAiB,OAAO,KAAK,IAAI;AAAA;AAAA,IACjC;AAAA,EACF;AACF;","names":[]}
import { DateInput } from './types.js';
/**
* Returns the difference between 2 dates in milliseconds.
* @param dateA A date to compare with the right date
* @param dateB A date to compare with the left date
*/
declare function diffMilliseconds(dateA: DateInput, dateB: DateInput): number;
export { diffMilliseconds };
// src/diffMilliseconds.ts
import { date } from "./date.mjs";
function diffMilliseconds(dateA, dateB) {
const left = date(dateA);
const right = date(dateB);
return +left - +right;
}
export {
diffMilliseconds
};
//# sourceMappingURL=diffMilliseconds.mjs.map
{"version":3,"sources":["../src/diffMilliseconds.ts"],"sourcesContent":["import { date } from \"./date\"\nimport { DateInput } from \"./types\"\n\n/**\n * Returns the difference between 2 dates in milliseconds.\n * @param dateA A date to compare with the right date\n * @param dateB A date to compare with the left date\n */\nexport function diffMilliseconds(dateA: DateInput, dateB: DateInput) {\n const left = date(dateA)\n const right = date(dateB)\n return +left - +right\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAQd,SAAS,iBAAiB,OAAkB,OAAkB;AACnE,QAAM,OAAO,KAAK,KAAK;AACvB,QAAM,QAAQ,KAAK,KAAK;AACxB,SAAO,CAAC,OAAO,CAAC;AAClB;","names":[]}
import { DateInput } from './types.js';
import { DiffRoundingMethod } from './diffRound.js';
/**
* Returns the difference between 2 dates in minutes.
* @param dateA A date to compare with the right date
* @param roundingMethod the rounding method to use, default: trunc
*/
declare function diffMinutes(dateA: DateInput, dateB: DateInput, roundingMethod?: DiffRoundingMethod): number;
export { diffMinutes };
// src/diffMinutes.ts
import { diffMilliseconds } from "./diffMilliseconds.mjs";
import { diffRound } from "./diffRound.mjs";
function diffMinutes(dateA, dateB, roundingMethod) {
return diffRound(diffMilliseconds(dateA, dateB) / 6e4, roundingMethod);
}
export {
diffMinutes
};
//# sourceMappingURL=diffMinutes.mjs.map
{"version":3,"sources":["../src/diffMinutes.ts"],"sourcesContent":["import { DateInput } from \"./types\"\nimport { diffMilliseconds } from \"./diffMilliseconds\"\nimport { diffRound, type DiffRoundingMethod } from \"./diffRound\"\n\n/**\n * Returns the difference between 2 dates in minutes.\n * @param dateA A date to compare with the right date\n * @param roundingMethod the rounding method to use, default: trunc\n */\nexport function diffMinutes(\n dateA: DateInput,\n dateB: DateInput,\n roundingMethod?: DiffRoundingMethod\n) {\n return diffRound(diffMilliseconds(dateA, dateB) / 60_000, roundingMethod)\n}\n"],"mappings":";AACA,SAAS,wBAAwB;AACjC,SAAS,iBAA0C;AAO5C,SAAS,YACd,OACA,OACA,gBACA;AACA,SAAO,UAAU,iBAAiB,OAAO,KAAK,IAAI,KAAQ,cAAc;AAC1E;","names":[]}
import { DateInput } from './types.js';
/**
* Returns the difference between 2 dates in months.
* @param dateA A date to compare with the dateB date
* @param dateB A date to compare with the dateA date
*/
declare function diffMonths(dateA: DateInput, dateB: DateInput): number;
export { diffMonths };
// src/diffMonths.ts
import { date } from "./date.mjs";
import { monthDays } from "./monthDays.mjs";
function diffMonths(dateA, dateB) {
const l = date(dateA);
const r = date(dateB);
if (l < r) {
const rs = diffMonths(r, l);
return rs == 0 ? 0 : -rs;
}
let months = (l.getFullYear() - r.getFullYear()) * 12 + (l.getMonth() - r.getMonth());
const ld = l.getDate();
const rd = r.getDate();
if (ld < rd) {
const lm = monthDays(l);
if (!(lm == ld && lm < rd)) {
months--;
}
}
return months == 0 ? 0 : months;
}
export {
diffMonths
};
//# sourceMappingURL=diffMonths.mjs.map
{"version":3,"sources":["../src/diffMonths.ts"],"sourcesContent":["import { date } from \"./date\"\nimport { DateInput } from \"./types\"\nimport { monthDays } from \"./monthDays\"\n\n/**\n * Returns the difference between 2 dates in months.\n * @param dateA A date to compare with the dateB date\n * @param dateB A date to compare with the dateA date\n */\nexport function diffMonths(dateA: DateInput, dateB: DateInput): number {\n const l = date(dateA)\n const r = date(dateB)\n // if the dateB one is bigger, we switch them around as it's easier to do\n if (l < r) {\n const rs = diffMonths(r, l)\n return rs == 0 ? 0 : -rs\n }\n\n // we first get the amount of calendar months\n let months =\n (l.getFullYear() - r.getFullYear()) * 12 + (l.getMonth() - r.getMonth())\n\n const ld = l.getDate()\n const rd = r.getDate()\n\n // if no full month has passed we may subtract a month from the calendar months so we get the amount of full months\n if (ld < rd) {\n // in case dateA date is the last day of the month & the dateB date is higher, we don't subtract as a full month did actually pass\n const lm = monthDays(l)\n if (!(lm == ld && lm < rd)) {\n months--\n }\n }\n //ensures we don't give back -0\n return months == 0 ? 0 : months\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAErB,SAAS,iBAAiB;AAOnB,SAAS,WAAW,OAAkB,OAA0B;AACrE,QAAM,IAAI,KAAK,KAAK;AACpB,QAAM,IAAI,KAAK,KAAK;AAEpB,MAAI,IAAI,GAAG;AACT,UAAM,KAAK,WAAW,GAAG,CAAC;AAC1B,WAAO,MAAM,IAAI,IAAI,CAAC;AAAA,EACxB;AAGA,MAAI,UACD,EAAE,YAAY,IAAI,EAAE,YAAY,KAAK,MAAM,EAAE,SAAS,IAAI,EAAE,SAAS;AAExE,QAAM,KAAK,EAAE,QAAQ;AACrB,QAAM,KAAK,EAAE,QAAQ;AAGrB,MAAI,KAAK,IAAI;AAEX,UAAM,KAAK,UAAU,CAAC;AACtB,QAAI,EAAE,MAAM,MAAM,KAAK,KAAK;AAC1B;AAAA,IACF;AAAA,EACF;AAEA,SAAO,UAAU,IAAI,IAAI;AAC3B;","names":[]}
type DiffRoundingMethod = "trunc" | "round" | "floor" | "ceil";
/**
* Return a rounded value with the given rounding method
* @param value the value to round
* @param method the rounding method
*/
declare function diffRound(value: number, method?: DiffRoundingMethod): number;
export { type DiffRoundingMethod, diffRound };
// src/diffRound.ts
function diffRound(value, method = "trunc") {
const r = Math[method](value);
return r == 0 ? 0 : r;
}
export {
diffRound
};
//# sourceMappingURL=diffRound.mjs.map
{"version":3,"sources":["../src/diffRound.ts"],"sourcesContent":["export type DiffRoundingMethod = \"trunc\" | \"round\" | \"floor\" | \"ceil\"\n\n/**\n * Return a rounded value with the given rounding method\n * @param value the value to round\n * @param method the rounding method\n */\nexport function diffRound(value: number, method: DiffRoundingMethod = \"trunc\") {\n const r = Math[method](value)\n return r == 0 ? 0 : r\n}\n"],"mappings":";AAOO,SAAS,UAAU,OAAe,SAA6B,SAAS;AAC7E,QAAM,IAAI,KAAK,MAAM,EAAE,KAAK;AAC5B,SAAO,KAAK,IAAI,IAAI;AACtB;","names":[]}
import { DiffRoundingMethod } from './diffRound.js';
import { DateInput } from './types.js';
/**
* Returns the difference between 2 dates in seconds.
* @param dateA A date to compare with the right date
* @param dateB A date to compare with the left date
* @param roundingMethod the rounding method to use, default: trunc
*/
declare function diffSeconds(dateA: DateInput, dateB: DateInput, roundingMethod?: DiffRoundingMethod): number;
export { diffSeconds };
// src/diffSeconds.ts
import { diffMilliseconds } from "./diffMilliseconds.mjs";
import { diffRound } from "./diffRound.mjs";
function diffSeconds(dateA, dateB, roundingMethod) {
return diffRound(diffMilliseconds(dateA, dateB) / 1e3, roundingMethod);
}
export {
diffSeconds
};
//# sourceMappingURL=diffSeconds.mjs.map
{"version":3,"sources":["../src/diffSeconds.ts"],"sourcesContent":["import { diffMilliseconds } from \"./diffMilliseconds\"\nimport { DiffRoundingMethod, diffRound } from \"./diffRound\"\nimport { DateInput } from \"./types\"\n\n/**\n * Returns the difference between 2 dates in seconds.\n * @param dateA A date to compare with the right date\n * @param dateB A date to compare with the left date\n * @param roundingMethod the rounding method to use, default: trunc\n */\nexport function diffSeconds(\n dateA: DateInput,\n dateB: DateInput,\n roundingMethod?: DiffRoundingMethod\n) {\n return diffRound(diffMilliseconds(dateA, dateB) / 1000, roundingMethod)\n}\n"],"mappings":";AAAA,SAAS,wBAAwB;AACjC,SAA6B,iBAAiB;AASvC,SAAS,YACd,OACA,OACA,gBACA;AACA,SAAO,UAAU,iBAAiB,OAAO,KAAK,IAAI,KAAM,cAAc;AACxE;","names":[]}
import { DateInput } from './types.js';
import { DiffRoundingMethod } from './diffRound.js';
/**
* Returns the difference between 2 dates in days.
* @param dateA A date to compare with the right date
* @param dateB A date to compare with the left date
* @param roundingMethod the rounding method to use, default: trunc
*/
declare function diffWeeks(dateA: DateInput, dateB: DateInput, roundingMethod?: DiffRoundingMethod): number;
export { diffWeeks };
// src/diffWeeks.ts
import { diffMilliseconds } from "./diffMilliseconds.mjs";
import { diffRound } from "./diffRound.mjs";
function diffWeeks(dateA, dateB, roundingMethod) {
return diffRound(
diffMilliseconds(dateA, dateB) / 6048e5,
// day * 7
roundingMethod
);
}
export {
diffWeeks
};
//# sourceMappingURL=diffWeeks.mjs.map
{"version":3,"sources":["../src/diffWeeks.ts"],"sourcesContent":["import { diffMilliseconds } from \"./diffMilliseconds\"\nimport { DateInput } from \"./types\"\nimport { diffRound, type DiffRoundingMethod } from \"./diffRound\"\n\n/**\n * Returns the difference between 2 dates in days.\n * @param dateA A date to compare with the right date\n * @param dateB A date to compare with the left date\n * @param roundingMethod the rounding method to use, default: trunc\n */\nexport function diffWeeks(\n dateA: DateInput,\n dateB: DateInput,\n roundingMethod?: DiffRoundingMethod\n) {\n return diffRound(\n diffMilliseconds(dateA, dateB) / 604800000, // day * 7\n roundingMethod\n )\n}\n"],"mappings":";AAAA,SAAS,wBAAwB;AAEjC,SAAS,iBAA0C;AAQ5C,SAAS,UACd,OACA,OACA,gBACA;AACA,SAAO;AAAA,IACL,iBAAiB,OAAO,KAAK,IAAI;AAAA;AAAA,IACjC;AAAA,EACF;AACF;","names":[]}
import { DateInput } from './types.js';
/**
* Returns the difference between 2 dates in years.
* @param dateA A date to compare with the dateB date
* @param dateB A date to compare with the dateA date
*/
declare function diffYears(dateA: DateInput, dateB: DateInput): number;
export { diffYears };
// src/diffYears.ts
import { diffMonths } from "./diffMonths.mjs";
function diffYears(dateA, dateB) {
const r = Math.trunc(diffMonths(dateA, dateB) / 12);
return r == 0 ? 0 : r;
}
export {
diffYears
};
//# sourceMappingURL=diffYears.mjs.map
{"version":3,"sources":["../src/diffYears.ts"],"sourcesContent":["import { diffMonths } from \"./diffMonths\"\nimport { DateInput } from \"./types\"\n\n/**\n * Returns the difference between 2 dates in years.\n * @param dateA A date to compare with the dateB date\n * @param dateB A date to compare with the dateA date\n */\nexport function diffYears(dateA: DateInput, dateB: DateInput): number {\n const r = Math.trunc(diffMonths(dateA, dateB) / 12)\n //ensures we don't give back -0\n return r == 0 ? 0 : r\n}\n"],"mappings":";AAAA,SAAS,kBAAkB;AAQpB,SAAS,UAAU,OAAkB,OAA0B;AACpE,QAAM,IAAI,KAAK,MAAM,WAAW,OAAO,KAAK,IAAI,EAAE;AAElD,SAAO,KAAK,IAAI,IAAI;AACtB;","names":[]}
import { FormatOptions, DateInput, Format, Part } from './types.js';
/**
* Produce a formatted string. Available strings:
* token | description
* ------|------------
* YY | 2 digit year
* YYYY | 4 digit year
* M | The month 1-12
* MM | The month 01-12
* MMM | Short name Jan-Dec
* MMMM | Full name January | December
* D | The day of the month 1-31
* DD | The day of the month 01-31
* d | Single digit day "T"
* ddd | Short day name Thu
* dddd | Full day name Wednesday
* H | Minimum hour digits, 24 hour, 0-23
* HH | 2 hour digits, 24 hour, 00-23
* h | Minimum hour digits, 12 hour clock, 1-12
* hh | 2 hour digits, 12 hour clock, 01-12
* m | The minute 0-59
* mm | The minute 00-59
* s | The second 0-59
* ss | The second 00-59
* a | am/pm
* A | AM/PM
* Z | +0800, +0530, -1345
*
* @param inputDate - A date object or ISO 8601 string
* @param format - A format
*/
declare function format(options: FormatOptions): string;
declare function format(inputDate: DateInput, format?: Format, locale?: string, genitive?: boolean, partFilter?: (part: Part) => boolean): string;
export { format };
// src/format.ts
import { date } from "./date.mjs";
import { parts } from "./parts.mjs";
import { fill, getOffsetFormat } from "./common.mjs";
import { offset } from "./offset.mjs";
import { removeOffset } from "./removeOffset.mjs";
import { deviceLocale } from "./deviceLocale.mjs";
import { deviceTZ } from "./deviceTZ.mjs";
function format(inputDateOrOptions, format2 = "long", locale = "device", genitive = false, partFilter) {
let tz, forceOffset;
if (typeof inputDateOrOptions === "object" && !(inputDateOrOptions instanceof Date)) {
;
({
date: inputDateOrOptions,
format: format2,
locale,
genitive,
partFilter,
tz
} = inputDateOrOptions);
}
if (format2 === "ISO8601")
return date(inputDateOrOptions).toISOString();
if (tz) {
forceOffset = offset(inputDateOrOptions, "utc", tz, getOffsetFormat(format2));
}
tz != null ? tz : tz = deviceTZ();
if ((tz == null ? void 0 : tz.toLowerCase()) !== "utc") {
inputDateOrOptions = removeOffset(
inputDateOrOptions,
offset(inputDateOrOptions, tz, "utc")
);
}
if (!locale || locale === "device") {
locale = deviceLocale();
}
return fill(
inputDateOrOptions,
parts(format2, locale).filter(partFilter != null ? partFilter : () => true),
locale,
genitive,
forceOffset
).map((p) => p.value).join("");
}
export {
format
};
//# sourceMappingURL=format.mjs.map
{"version":3,"sources":["../src/format.ts"],"sourcesContent":["import { date } from \"./date\"\nimport { parts } from \"./parts\"\nimport { fill, getOffsetFormat } from \"./common\"\nimport type { DateInput, Format, FormatOptions, FormatStyle, Part } from \"./types\"\nimport { offset } from \"./offset\"\nimport { removeOffset } from \"./removeOffset\"\nimport { deviceLocale } from \"./deviceLocale\"\nimport { deviceTZ } from \"./deviceTZ\"\n\n/**\n * Produce a formatted string. Available strings:\n * token | description\n * ------|------------\n * YY | 2 digit year\n * YYYY | 4 digit year\n * M | The month 1-12\n * MM | The month 01-12\n * MMM | Short name Jan-Dec\n * MMMM | Full name January | December\n * D | The day of the month 1-31\n * DD | The day of the month 01-31\n * d | Single digit day \"T\"\n * ddd | Short day name Thu\n * dddd | Full day name Wednesday\n * H | Minimum hour digits, 24 hour, 0-23\n * HH | 2 hour digits, 24 hour, 00-23\n * h | Minimum hour digits, 12 hour clock, 1-12\n * hh | 2 hour digits, 12 hour clock, 01-12\n * m | The minute 0-59\n * mm | The minute 00-59\n * s | The second 0-59\n * ss | The second 00-59\n * a | am/pm\n * A | AM/PM\n * Z | +0800, +0530, -1345\n *\n * @param inputDate - A date object or ISO 8601 string\n * @param format - A format\n */\nexport function format(options: FormatOptions): string\nexport function format(\n inputDate: DateInput,\n format?: Format,\n locale?: string,\n genitive?: boolean,\n partFilter?: (part: Part) => boolean\n): string\nexport function format(\n inputDateOrOptions: DateInput | FormatOptions,\n format: Format = \"long\",\n locale: string | undefined = \"device\",\n genitive: boolean | undefined = false,\n partFilter?: (part: Part) => boolean\n): string {\n let tz: string | undefined, forceOffset: string | undefined\n\n if (\n typeof inputDateOrOptions === \"object\" &&\n !(inputDateOrOptions instanceof Date)\n ) {\n // Extract options from the object.\n ;({\n date: inputDateOrOptions,\n format,\n locale,\n genitive,\n partFilter,\n tz,\n } = inputDateOrOptions)\n }\n // ISO 8601 is a special case because it doesn't require a format.\n if (format === \"ISO8601\") return date(inputDateOrOptions).toISOString()\n\n if (tz) {\n forceOffset = offset(inputDateOrOptions, \"utc\", tz, getOffsetFormat(format))\n }\n\n // We need to apply an offset to the date so that it can be formatted as UTC.\n tz ??= deviceTZ()\n if (tz?.toLowerCase() !== \"utc\") {\n inputDateOrOptions = removeOffset(\n inputDateOrOptions,\n offset(inputDateOrOptions, tz, \"utc\")\n )\n }\n\n if (!locale || locale === \"device\") {\n locale = deviceLocale()\n }\n\n return fill(\n inputDateOrOptions,\n parts(format, locale).filter(partFilter ?? (() => true)),\n locale,\n genitive,\n forceOffset\n )\n .map((p) => p.value)\n .join(\"\")\n}\n"],"mappings":";AAAA,SAAS,YAAY;AACrB,SAAS,aAAa;AACtB,SAAS,MAAM,uBAAuB;AAEtC,SAAS,cAAc;AACvB,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AAC7B,SAAS,gBAAgB;AAwClB,SAAS,OACd,oBACAA,UAAiB,QACjB,SAA6B,UAC7B,WAAgC,OAChC,YACQ;AACR,MAAI,IAAwB;AAE5B,MACE,OAAO,uBAAuB,YAC9B,EAAE,8BAA8B,OAChC;AAEA;AAAC,KAAC;AAAA,MACA,MAAM;AAAA,MACN,QAAAA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,IAAI;AAAA,EACN;AAEA,MAAIA,YAAW;AAAW,WAAO,KAAK,kBAAkB,EAAE,YAAY;AAEtE,MAAI,IAAI;AACN,kBAAc,OAAO,oBAAoB,OAAO,IAAI,gBAAgBA,OAAM,CAAC;AAAA,EAC7E;AAGA,yBAAO,SAAS;AAChB,OAAI,yBAAI,mBAAkB,OAAO;AAC/B,yBAAqB;AAAA,MACnB;AAAA,MACA,OAAO,oBAAoB,IAAI,KAAK;AAAA,IACtC;AAAA,EACF;AAEA,MAAI,CAAC,UAAU,WAAW,UAAU;AAClC,aAAS,aAAa;AAAA,EACxB;AAEA,SAAO;AAAA,IACL;AAAA,IACA,MAAMA,SAAQ,MAAM,EAAE,OAAO,kCAAe,MAAM,IAAK;AAAA,IACvD;AAAA,IACA;AAAA,IACA;AAAA,EACF,EACG,IAAI,CAAC,MAAM,EAAE,KAAK,EAClB,KAAK,EAAE;AACZ;","names":["format"]}
import { Format, Part } from './types.js';
/**
* Return the string format for a given format. For example:
* ```js
* formatStr({ date: 'long' }, 'en') // dddd, MMMM D, YYYY
* ```
* @param format - A format string or object.
* @param locale - A locale or en by default.
*/
declare function formatStr(format: Format, locale?: string, escapeLiterals?: boolean, filterParts?: (part: Part) => boolean): string;
export { formatStr };
// src/formatStr.ts
import { parts } from "./parts.mjs";
import { escapeTokens } from "./common.mjs";
function formatStr(format, locale = "en", escapeLiterals = false, filterParts = () => true) {
return parts(format, locale).filter(filterParts).reduce(
(f, p) => f += escapeLiterals && p.partName === "literal" ? escapeTokens(p.token) : p.token,
""
).normalize("NFKC");
}
export {
formatStr
};
//# sourceMappingURL=formatStr.mjs.map
{"version":3,"sources":["../src/formatStr.ts"],"sourcesContent":["import { parts } from \"./parts\"\nimport { escapeTokens } from \"./common\"\nimport type { Format, Part } from \"./types\"\n\n/**\n * Return the string format for a given format. For example:\n * ```js\n * formatStr({ date: 'long' }, 'en') // dddd, MMMM D, YYYY\n * ```\n * @param format - A format string or object.\n * @param locale - A locale or en by default.\n */\nexport function formatStr(\n format: Format,\n locale = \"en\",\n escapeLiterals = false,\n filterParts: (part: Part) => boolean = () => true\n): string {\n return parts(format, locale)\n .filter(filterParts)\n .reduce(\n (f, p) =>\n (f +=\n escapeLiterals && p.partName === \"literal\"\n ? escapeTokens(p.token)\n : p.token),\n \"\"\n )\n .normalize(\"NFKC\")\n}\n"],"mappings":";AAAA,SAAS,aAAa;AACtB,SAAS,oBAAoB;AAWtB,SAAS,UACd,QACA,SAAS,MACT,iBAAiB,OACjB,cAAuC,MAAM,MACrC;AACR,SAAO,MAAM,QAAQ,MAAM,EACxB,OAAO,WAAW,EAClB;AAAA,IACC,CAAC,GAAG,MACD,KACC,kBAAkB,EAAE,aAAa,YAC7B,aAAa,EAAE,KAAK,IACpB,EAAE;AAAA,IACV;AAAA,EACF,EACC,UAAU,MAAM;AACrB;","names":[]}
/**
* Converts a 2 digit year into a 4 digit year. This function assumes years 20
* years into the future belong to the current century, and the past 80 are in
* the past.
*
* @param value - 2 digits in string format
*/
declare function fourDigitYear(value: string): number;
export { fourDigitYear };
// src/fourDigitYear.ts
function fourDigitYear(value) {
const y = (/* @__PURE__ */ new Date()).getFullYear();
const currentYear = y % 100;
const century = Math.floor(y / 100);
const parsedYear = Number(value);
return (century + (parsedYear > currentYear + 20 ? -1 : 0)) * 100 + parsedYear;
}
export {
fourDigitYear
};
//# sourceMappingURL=fourDigitYear.mjs.map
{"version":3,"sources":["../src/fourDigitYear.ts"],"sourcesContent":["/**\n * Converts a 2 digit year into a 4 digit year. This function assumes years 20\n * years into the future belong to the current century, and the past 80 are in\n * the past.\n *\n * @param value - 2 digits in string format\n */\nexport function fourDigitYear(value: string): number {\n const y = new Date().getFullYear()\n const currentYear = y % 100\n const century = Math.floor(y / 100)\n const parsedYear = Number(value)\n return (century + (parsedYear > currentYear + 20 ? -1 : 0)) * 100 + parsedYear\n}\n"],"mappings":";AAOO,SAAS,cAAc,OAAuB;AACnD,QAAM,KAAI,oBAAI,KAAK,GAAE,YAAY;AACjC,QAAM,cAAc,IAAI;AACxB,QAAM,UAAU,KAAK,MAAM,IAAI,GAAG;AAClC,QAAM,aAAa,OAAO,KAAK;AAC/B,UAAQ,WAAW,aAAa,cAAc,KAAK,KAAK,MAAM,MAAM;AACtE;","names":[]}
import { DateInput } from './types.js';
/**
* Returns a Date object for end of the given hour.
* @param inputDate - A string or Date object
*/
declare function hourEnd(inputDate: DateInput): Date;
export { hourEnd };
// src/hourEnd.ts
import { date } from "./date.mjs";
function hourEnd(inputDate) {
const d = date(inputDate);
d.setMinutes(59, 59, 999);
return d;
}
export {
hourEnd
};
//# sourceMappingURL=hourEnd.mjs.map
{"version":3,"sources":["../src/hourEnd.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Returns a Date object for end of the given hour.\n * @param inputDate - A string or Date object\n */\nexport function hourEnd(inputDate: DateInput): Date {\n const d = date(inputDate)\n d.setMinutes(59, 59, 999)\n return d\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAOd,SAAS,QAAQ,WAA4B;AAClD,QAAM,IAAI,KAAK,SAAS;AACxB,IAAE,WAAW,IAAI,IAAI,GAAG;AACxB,SAAO;AACT;","names":[]}
import { DateInput } from './types.js';
/**
* Returns a Date object for start of the given hour.
* @param inputDate - A string or Date object
*/
declare function hourStart(inputDate: DateInput): Date;
export { hourStart };
// src/hourStart.ts
import { date } from "./date.mjs";
function hourStart(inputDate) {
const d = date(inputDate);
d.setMinutes(0, 0);
return d;
}
export {
hourStart
};
//# sourceMappingURL=hourStart.mjs.map
{"version":3,"sources":["../src/hourStart.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Returns a Date object for start of the given hour.\n * @param inputDate - A string or Date object\n */\nexport function hourStart(inputDate: DateInput): Date {\n const d = date(inputDate)\n d.setMinutes(0, 0)\n return d\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAOd,SAAS,UAAU,WAA4B;AACpD,QAAM,IAAI,KAAK,SAAS;AACxB,IAAE,WAAW,GAAG,CAAC;AACjB,SAAO;AACT;","names":[]}
import { DateInput } from './types.js';
/**
* @name isAfter
* @category Common Helpers
* @summary Is the first date after the second one?
*
* @description
* Is the first date after the second one?
*
* @param inputDate - The date that should be after the other one to return true
* @param dateToCompare - The date to compare with
*
* @returns The first date is after the second date.
*/
declare function isAfter(inputDate: DateInput, dateToCompare: DateInput): boolean;
export { isAfter };
// src/isAfter.ts
import { date } from "./date.mjs";
function isAfter(inputDate, dateToCompare) {
const _date = date(inputDate);
const _dateToCompare = date(dateToCompare);
return +_date > +_dateToCompare;
}
export {
isAfter
};
//# sourceMappingURL=isAfter.mjs.map
{"version":3,"sources":["../src/isAfter.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { DateInput } from \"./types\"\n\n/**\n * @name isAfter\n * @category Common Helpers\n * @summary Is the first date after the second one?\n *\n * @description\n * Is the first date after the second one?\n *\n * @param inputDate - The date that should be after the other one to return true\n * @param dateToCompare - The date to compare with\n *\n * @returns The first date is after the second date.\n */\nexport function isAfter(inputDate: DateInput, dateToCompare: DateInput) {\n const _date = date(inputDate)\n const _dateToCompare = date(dateToCompare)\n\n return +_date > +_dateToCompare\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAgBd,SAAS,QAAQ,WAAsB,eAA0B;AACtE,QAAM,QAAQ,KAAK,SAAS;AAC5B,QAAM,iBAAiB,KAAK,aAAa;AAEzC,SAAO,CAAC,QAAQ,CAAC;AACnB;","names":[]}
import { DateInput } from './types.js';
/**
* Is the first date before the second one?
*
* @param inputDate - The date that should be before the other one to return true
* @param dateToCompare - The date to compare with
*
* @returns The first date is before the second date.
*/
declare function isBefore(inputDate: DateInput, dateToCompare: DateInput): boolean;
export { isBefore };
// src/isBefore.ts
import { date } from "./date.mjs";
function isBefore(inputDate, dateToCompare) {
const _date = date(inputDate);
const _dateToCompare = date(dateToCompare);
return +_date < +_dateToCompare;
}
export {
isBefore
};
//# sourceMappingURL=isBefore.mjs.map
{"version":3,"sources":["../src/isBefore.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Is the first date before the second one?\n *\n * @param inputDate - The date that should be before the other one to return true\n * @param dateToCompare - The date to compare with\n *\n * @returns The first date is before the second date.\n */\nexport function isBefore(inputDate: DateInput, dateToCompare: DateInput) {\n const _date = date(inputDate)\n const _dateToCompare = date(dateToCompare)\n\n return +_date < +_dateToCompare\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAWd,SAAS,SAAS,WAAsB,eAA0B;AACvE,QAAM,QAAQ,KAAK,SAAS;AAC5B,QAAM,iBAAiB,KAAK,aAAa;AAEzC,SAAO,CAAC,QAAQ,CAAC;AACnB;","names":[]}
import { DateInput } from './types.js';
/**
* Are the given dates equal?
*
* @param dateLeft - The first date to compare
* @param dateRight - The second date to compare
*
* @returns The dates are equal.
*/
declare function isEqual(dateLeft: DateInput, dateRight: DateInput): boolean;
export { isEqual };
// src/isEqual.ts
import { date } from "./date.mjs";
function isEqual(dateLeft, dateRight) {
const _dateLeft = date(dateLeft);
const _dateRight = date(dateRight);
return +_dateLeft === +_dateRight;
}
export {
isEqual
};
//# sourceMappingURL=isEqual.mjs.map
{"version":3,"sources":["../src/isEqual.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Are the given dates equal?\n *\n * @param dateLeft - The first date to compare\n * @param dateRight - The second date to compare\n *\n * @returns The dates are equal.\n */\nexport function isEqual(dateLeft: DateInput, dateRight: DateInput) {\n const _dateLeft = date(dateLeft)\n const _dateRight = date(dateRight)\n\n return +_dateLeft === +_dateRight\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAWd,SAAS,QAAQ,UAAqB,WAAsB;AACjE,QAAM,YAAY,KAAK,QAAQ;AAC/B,QAAM,aAAa,KAAK,SAAS;AAEjC,SAAO,CAAC,cAAc,CAAC;AACzB;","names":[]}
/**
* Matches a given date with ISO 8601 compliance. Allows the "T" to be missing
* and only requires year and month, other params are required with increasing
* specificity.
*/
declare const iso8601Match: RegExp;
/**
* True when the date string is valid ISO 8601.
* @param date - A date string.
*/
declare function iso8601(date: string): boolean;
export { iso8601, iso8601Match };
// src/iso8601.ts
var iso8601Match = /^([0-9]{4})-([0-1][0-9])(?:-([0-3][0-9]))?(?:[T ]?([0-2][0-9])(?::([0-5][0-9]))?(?::([0-5][0-9]))?)?(?:\.[0-9]+)?(Z|(?:\+|\-)[0-9]{2}:?[0-9]{2})?$/;
function iso8601(date) {
const matches = date.match(iso8601Match);
if (matches) {
const month = Number(matches[2]);
if (month < 1 || month > 12)
return false;
if (typeof matches[3] !== void 0) {
const date2 = Number(matches[3]);
if (date2 < 1 || date2 > 31)
return false;
}
if (typeof matches[4] !== void 0) {
const hours = Number(matches[4]);
if (hours < 0 || hours > 23)
return false;
}
return true;
}
return false;
}
export {
iso8601,
iso8601Match
};
//# sourceMappingURL=iso8601.mjs.map
{"version":3,"sources":["../src/iso8601.ts"],"sourcesContent":["/**\n * Matches a given date with ISO 8601 compliance. Allows the \"T\" to be missing\n * and only requires year and month, other params are required with increasing\n * specificity.\n */\nexport const iso8601Match =\n /^([0-9]{4})-([0-1][0-9])(?:-([0-3][0-9]))?(?:[T ]?([0-2][0-9])(?::([0-5][0-9]))?(?::([0-5][0-9]))?)?(?:\\.[0-9]+)?(Z|(?:\\+|\\-)[0-9]{2}:?[0-9]{2})?$/\n\n/**\n * True when the date string is valid ISO 8601.\n * @param date - A date string.\n */\nexport function iso8601(date: string): boolean {\n const matches = date.match(iso8601Match)\n if (matches) {\n const month = Number(matches[2])\n if (month < 1 || month > 12) return false\n\n if (typeof matches[3] !== undefined) {\n const date = Number(matches[3])\n if (date < 1 || date > 31) return false\n }\n if (typeof matches[4] !== undefined) {\n const hours = Number(matches[4])\n if (hours < 0 || hours > 23) return false\n }\n\n return true\n }\n return false\n}\n"],"mappings":";AAKO,IAAM,eACX;AAMK,SAAS,QAAQ,MAAuB;AAC7C,QAAM,UAAU,KAAK,MAAM,YAAY;AACvC,MAAI,SAAS;AACX,UAAM,QAAQ,OAAO,QAAQ,CAAC,CAAC;AAC/B,QAAI,QAAQ,KAAK,QAAQ;AAAI,aAAO;AAEpC,QAAI,OAAO,QAAQ,CAAC,MAAM,QAAW;AACnC,YAAMA,QAAO,OAAO,QAAQ,CAAC,CAAC;AAC9B,UAAIA,QAAO,KAAKA,QAAO;AAAI,eAAO;AAAA,IACpC;AACA,QAAI,OAAO,QAAQ,CAAC,MAAM,QAAW;AACnC,YAAM,QAAQ,OAAO,QAAQ,CAAC,CAAC;AAC/B,UAAI,QAAQ,KAAK,QAAQ;AAAI,eAAO;AAAA,IACtC;AAEA,WAAO;AAAA,EACT;AACA,SAAO;AACT;","names":["date"]}
import { DateInput } from './types.js';
/**
* Returns a Date object for end of the given minute.
* @param inputDate - A string or Date object
*/
declare function minuteEnd(inputDate: DateInput): Date;
export { minuteEnd };
// src/minuteEnd.ts
import { date } from "./date.mjs";
function minuteEnd(inputDate) {
const d = date(inputDate);
d.setSeconds(59, 999);
return d;
}
export {
minuteEnd
};
//# sourceMappingURL=minuteEnd.mjs.map
{"version":3,"sources":["../src/minuteEnd.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Returns a Date object for end of the given minute.\n * @param inputDate - A string or Date object\n */\nexport function minuteEnd(inputDate: DateInput): Date {\n const d = date(inputDate)\n d.setSeconds(59, 999)\n return d\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAOd,SAAS,UAAU,WAA4B;AACpD,QAAM,IAAI,KAAK,SAAS;AACxB,IAAE,WAAW,IAAI,GAAG;AACpB,SAAO;AACT;","names":[]}
import { DateInput } from './types.js';
/**
* Returns a Date object for start of the given minute.
* @param inputDate - A string or Date object
*/
declare function minuteStart(inputDate: DateInput): Date;
export { minuteStart };
// src/minuteStart.ts
import { date } from "./date.mjs";
function minuteStart(inputDate) {
const d = date(inputDate);
d.setSeconds(0);
return d;
}
export {
minuteStart
};
//# sourceMappingURL=minuteStart.mjs.map
{"version":3,"sources":["../src/minuteStart.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Returns a Date object for start of the given minute.\n * @param inputDate - A string or Date object\n */\nexport function minuteStart(inputDate: DateInput): Date {\n const d = date(inputDate)\n d.setSeconds(0)\n return d\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAOd,SAAS,YAAY,WAA4B;AACtD,QAAM,IAAI,KAAK,SAAS;AACxB,IAAE,WAAW,CAAC;AACd,SAAO;AACT;","names":[]}
import { DateInput } from './types.js';
/**
* Returns the total number of days from a given month.
* @param inputDate - A string or Date object
*/
declare function monthDays(inputDate: DateInput): number;
export { monthDays };
// src/monthDays.ts
import { monthEnd } from "./monthEnd.mjs";
function monthDays(inputDate) {
const d = monthEnd(inputDate);
return d.getDate();
}
export {
monthDays
};
//# sourceMappingURL=monthDays.mjs.map
{"version":3,"sources":["../src/monthDays.ts"],"sourcesContent":["import { monthEnd } from \"./monthEnd\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Returns the total number of days from a given month.\n * @param inputDate - A string or Date object\n */\nexport function monthDays(inputDate: DateInput): number {\n const d = monthEnd(inputDate)\n return d.getDate()\n}\n"],"mappings":";AAAA,SAAS,gBAAgB;AAOlB,SAAS,UAAU,WAA8B;AACtD,QAAM,IAAI,SAAS,SAAS;AAC5B,SAAO,EAAE,QAAQ;AACnB;","names":[]}
import { DateInput } from './types.js';
/**
* Returns a Date object for the with the input date set to the last day of
* the current month. Does not change the time.
* @param inputDate - A string or Date object
*/
declare function monthEnd(inputDate: DateInput): Date;
export { monthEnd };
// src/monthEnd.ts
import { date } from "./date.mjs";
function monthEnd(inputDate) {
const d = date(inputDate);
d.setDate(1);
d.setMonth(d.getMonth() + 1);
d.setDate(0);
return d;
}
export {
monthEnd
};
//# sourceMappingURL=monthEnd.mjs.map
{"version":3,"sources":["../src/monthEnd.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Returns a Date object for the with the input date set to the last day of\n * the current month. Does not change the time.\n * @param inputDate - A string or Date object\n */\nexport function monthEnd(inputDate: DateInput): Date {\n const d = date(inputDate)\n d.setDate(1)\n d.setMonth(d.getMonth() + 1)\n d.setDate(0)\n return d\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAQd,SAAS,SAAS,WAA4B;AACnD,QAAM,IAAI,KAAK,SAAS;AACxB,IAAE,QAAQ,CAAC;AACX,IAAE,SAAS,EAAE,SAAS,IAAI,CAAC;AAC3B,IAAE,QAAQ,CAAC;AACX,SAAO;AACT;","names":[]}
import { DateInput } from './types.js';
/**
* Returns a Date object for the first day of a month.
* @param inputDate - A string or Date object
*/
declare function monthStart(inputDate: DateInput): Date;
export { monthStart };
// src/monthStart.ts
import { date } from "./date.mjs";
function monthStart(inputDate) {
const d = date(inputDate);
d.setDate(1);
d.setHours(0, 0, 0);
return d;
}
export {
monthStart
};
//# sourceMappingURL=monthStart.mjs.map
{"version":3,"sources":["../src/monthStart.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Returns a Date object for the first day of a month.\n * @param inputDate - A string or Date object\n */\nexport function monthStart(inputDate: DateInput): Date {\n const d = date(inputDate)\n d.setDate(1)\n d.setHours(0, 0, 0)\n return d\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAOd,SAAS,WAAW,WAA4B;AACrD,QAAM,IAAI,KAAK,SAAS;AACxB,IAAE,QAAQ,CAAC;AACX,IAAE,SAAS,GAAG,GAAG,CAAC;AAClB,SAAO;AACT;","names":[]}
import { DateInput } from './types.js';
/**
* Performs a bidirectional search for the nearest date that passes a function.
* @param target - Performs a search for the nearest passing date.
* @param search - The search function to use, given a date returns a boolean.
* @param constraint - The number of iterations to perform before giving up, or logical constraint like "month", or "week".
*
*/
declare function nearestDay(inputDate: DateInput, search: (date: Date) => boolean, constraint?: number | "month" | "week" | "year"): Date | null;
export { nearestDay };
// src/nearestDay.ts
import { date } from "./date.mjs";
import { monthDays } from "./monthDays.mjs";
import { yearDays } from "./yearDays.mjs";
import { dayOfYear } from "./dayOfYear.mjs";
import { addDay } from "./addDay.mjs";
function nearestDay(inputDate, search, constraint = 7) {
let increments;
let decrements;
const d = date(inputDate);
switch (constraint) {
case "month":
decrements = d.getDate();
increments = monthDays(d) - d.getDate();
break;
case "week":
decrements = d.getDay() + 1;
increments = 6 - d.getDay();
break;
case "year":
const total = yearDays(d);
const day = dayOfYear(d);
decrements = day;
increments = total - day;
break;
default:
increments = decrements = constraint;
}
for (let i = 0; i <= increments || i < decrements; i++) {
if (i <= increments) {
const next = addDay(d, i);
if (search(next))
return next;
}
if (i && i <= decrements) {
const prev = addDay(d, -i);
if (search(prev))
return prev;
}
}
return null;
}
export {
nearestDay
};
//# sourceMappingURL=nearestDay.mjs.map
{"version":3,"sources":["../src/nearestDay.ts"],"sourcesContent":["import { date } from \"./date\"\nimport { monthDays } from \"./monthDays\"\nimport { yearDays } from \"./yearDays\"\nimport { dayOfYear } from \"./dayOfYear\"\nimport { addDay } from \"./addDay\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Performs a bidirectional search for the nearest date that passes a function.\n * @param target - Performs a search for the nearest passing date.\n * @param search - The search function to use, given a date returns a boolean.\n * @param constraint - The number of iterations to perform before giving up, or logical constraint like \"month\", or \"week\".\n *\n */\nexport function nearestDay(\n inputDate: DateInput,\n search: (date: Date) => boolean,\n constraint: number | \"month\" | \"week\" | \"year\" = 7\n): Date | null {\n let increments: number\n let decrements: number\n const d = date(inputDate)\n switch (constraint) {\n case \"month\":\n decrements = d.getDate()\n increments = monthDays(d) - d.getDate()\n break\n case \"week\":\n decrements = d.getDay() + 1\n increments = 6 - d.getDay()\n break\n case \"year\":\n const total = yearDays(d)\n const day = dayOfYear(d)\n decrements = day\n increments = total - day\n break\n default:\n increments = decrements = constraint\n }\n\n for (let i = 0; i <= increments || i < decrements; i++) {\n if (i <= increments) {\n const next = addDay(d, i)\n if (search(next)) return next\n }\n if (i && i <= decrements) {\n const prev = addDay(d, -i)\n if (search(prev)) return prev\n }\n }\n return null\n}\n"],"mappings":";AAAA,SAAS,YAAY;AACrB,SAAS,iBAAiB;AAC1B,SAAS,gBAAgB;AACzB,SAAS,iBAAiB;AAC1B,SAAS,cAAc;AAUhB,SAAS,WACd,WACA,QACA,aAAiD,GACpC;AACb,MAAI;AACJ,MAAI;AACJ,QAAM,IAAI,KAAK,SAAS;AACxB,UAAQ,YAAY;AAAA,IAClB,KAAK;AACH,mBAAa,EAAE,QAAQ;AACvB,mBAAa,UAAU,CAAC,IAAI,EAAE,QAAQ;AACtC;AAAA,IACF,KAAK;AACH,mBAAa,EAAE,OAAO,IAAI;AAC1B,mBAAa,IAAI,EAAE,OAAO;AAC1B;AAAA,IACF,KAAK;AACH,YAAM,QAAQ,SAAS,CAAC;AACxB,YAAM,MAAM,UAAU,CAAC;AACvB,mBAAa;AACb,mBAAa,QAAQ;AACrB;AAAA,IACF;AACE,mBAAa,aAAa;AAAA,EAC9B;AAEA,WAAS,IAAI,GAAG,KAAK,cAAc,IAAI,YAAY,KAAK;AACtD,QAAI,KAAK,YAAY;AACnB,YAAM,OAAO,OAAO,GAAG,CAAC;AACxB,UAAI,OAAO,IAAI;AAAG,eAAO;AAAA,IAC3B;AACA,QAAI,KAAK,KAAK,YAAY;AACxB,YAAM,OAAO,OAAO,GAAG,CAAC,CAAC;AACzB,UAAI,OAAO,IAAI;AAAG,eAAO;AAAA,IAC3B;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
import { TimezoneToken } from './common.js';
import { DateInput } from './types.js';
/**
* Returns the offset between two timezones on a given date. The results are
* ISO8601 compatible offsets like -0800 or +0530.
*
* @param dateInput - The date on which to determine the offset.
* @param tzA - (default: UTC) The second timezone to compare determine the offset between.
* @param tzB - (default: device) The first timezone to compare determine the offset between.
*/
declare function offset(utcTime: DateInput, tzA?: string, tzB?: string, timeZoneToken?: TimezoneToken): string;
export { offset };
// src/offset.ts
import { date } from "./date.mjs";
import { normStr, minsToOffset } from "./common.mjs";
import { deviceTZ } from "./deviceTZ.mjs";
function relativeTime(d, timeZone) {
const utcParts = new Intl.DateTimeFormat("en-US", {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
timeZone,
hourCycle: "h23"
}).formatToParts(d).map(normStr);
const parts = {};
utcParts.forEach((part) => {
parts[part.type] = part.value;
});
return /* @__PURE__ */ new Date(
`${parts.year}-${parts.month}-${parts.day}T${parts.hour}:${parts.minute}:${parts.second}Z`
);
}
function offset(utcTime, tzA = "UTC", tzB = "device", timeZoneToken = "Z") {
var _a;
tzB = tzB === "device" ? (_a = deviceTZ()) != null ? _a : "utc" : tzB;
const d = date(utcTime);
const timeA = relativeTime(d, tzA);
const timeB = relativeTime(d, tzB);
const timeDiffInMins = (timeB.getTime() - timeA.getTime()) / 1e3 / 60;
return minsToOffset(timeDiffInMins, timeZoneToken);
}
export {
offset
};
//# sourceMappingURL=offset.mjs.map
{"version":3,"sources":["../src/offset.ts"],"sourcesContent":["import { date } from \"./date\"\nimport { normStr, minsToOffset, TimezoneToken } from \"./common\"\nimport { deviceTZ } from \"./deviceTZ\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Converts a date object from one timezone to that same time in UTC. This is\n * only for internal use.\n * @param d - A Date object\n * @param timeZone - A timezone string\n */\nfunction relativeTime(d: Date, timeZone: string): Date {\n const utcParts = new Intl.DateTimeFormat(\"en-US\", {\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n timeZone,\n hourCycle: \"h23\",\n })\n .formatToParts(d)\n .map(normStr)\n const parts: {\n year?: string\n month?: string\n day?: string\n hour?: string\n minute?: string\n second?: string\n } = {}\n utcParts.forEach((part) => {\n parts[part.type as keyof typeof parts] = part.value\n })\n return new Date(\n `${parts.year}-${parts.month}-${parts.day}T${parts.hour}:${parts.minute}:${parts.second}Z`\n )\n}\n\n/**\n * Returns the offset between two timezones on a given date. The results are\n * ISO8601 compatible offsets like -0800 or +0530.\n *\n * @param dateInput - The date on which to determine the offset.\n * @param tzA - (default: UTC) The second timezone to compare determine the offset between.\n * @param tzB - (default: device) The first timezone to compare determine the offset between.\n */\nexport function offset(\n utcTime: DateInput,\n tzA = \"UTC\",\n tzB = \"device\",\n timeZoneToken: TimezoneToken = \"Z\" ,\n): string {\n tzB = tzB === \"device\" ? deviceTZ() ?? \"utc\" : tzB\n const d = date(utcTime)\n const timeA = relativeTime(d, tzA)\n const timeB = relativeTime(d, tzB)\n const timeDiffInMins = (timeB.getTime() - timeA.getTime()) / 1000 / 60\n return minsToOffset(timeDiffInMins, timeZoneToken)\n}\n"],"mappings":";AAAA,SAAS,YAAY;AACrB,SAAS,SAAS,oBAAmC;AACrD,SAAS,gBAAgB;AASzB,SAAS,aAAa,GAAS,UAAwB;AACrD,QAAM,WAAW,IAAI,KAAK,eAAe,SAAS;AAAA,IAChD,MAAM;AAAA,IACN,OAAO;AAAA,IACP,KAAK;AAAA,IACL,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR;AAAA,IACA,WAAW;AAAA,EACb,CAAC,EACE,cAAc,CAAC,EACf,IAAI,OAAO;AACd,QAAM,QAOF,CAAC;AACL,WAAS,QAAQ,CAAC,SAAS;AACzB,UAAM,KAAK,IAA0B,IAAI,KAAK;AAAA,EAChD,CAAC;AACD,SAAO,oBAAI;AAAA,IACT,GAAG,MAAM,IAAI,IAAI,MAAM,KAAK,IAAI,MAAM,GAAG,IAAI,MAAM,IAAI,IAAI,MAAM,MAAM,IAAI,MAAM,MAAM;AAAA,EACzF;AACF;AAUO,SAAS,OACd,SACA,MAAM,OACN,MAAM,UACN,gBAA+B,KACvB;AArDV;AAsDE,QAAM,QAAQ,YAAW,cAAS,MAAT,YAAc,QAAQ;AAC/C,QAAM,IAAI,KAAK,OAAO;AACtB,QAAM,QAAQ,aAAa,GAAG,GAAG;AACjC,QAAM,QAAQ,aAAa,GAAG,GAAG;AACjC,QAAM,kBAAkB,MAAM,QAAQ,IAAI,MAAM,QAAQ,KAAK,MAAO;AACpE,SAAO,aAAa,gBAAgB,aAAa;AACnD;","names":[]}
import { ParseOptions, Format, Part, FilledPart } from './types.js';
declare function parse(options: ParseOptions): Date | never;
declare function parse(dateStr: string, format?: Format, locale?: string): Date | never;
/**
* Given a string date and corresponding format parts, fill the parts with the
* data from the string.
* @param dateStr - A string to parse.
* @param formatParts - The expected parts of the given string.
*/
declare function parseParts(dateStr: string, formatParts: Part[]): FilledPart[];
export { parse, parseParts };
// src/parse.ts
import { date } from "./date.mjs";
import { validate, styles, fixedLength, four, two, validOffset, fixedLengthByOffset } from "./common.mjs";
import { formatStr } from "./formatStr.mjs";
import { fourDigitYear } from "./fourDigitYear.mjs";
import { ap } from "./ap.mjs";
import { range } from "./range.mjs";
import { monthDays } from "./monthDays.mjs";
import { parts } from "./parts.mjs";
function parse(dateStrOrOptions, format = "ISO8601", locale = "device") {
let partFilter = () => true;
let dateStr;
let dateOverflow = "backward";
if (typeof dateStrOrOptions === "object") {
;
({
date: dateStr,
format = "ISO8601",
locale = "device",
dateOverflow = "backward",
partFilter = () => true
} = dateStrOrOptions);
} else {
dateStr = dateStrOrOptions;
}
if (!dateStr)
throw new Error("parse() requires a date string.");
const invalid = () => {
throw new Error(
`Date (${dateStr}) does not match format (${formatStr(format, locale)})`
);
};
if (format === "ISO8601")
return date(dateStr);
const genitive = styles.includes(format) || typeof format === "object";
const formatParts = validate(parts(format, locale).filter(partFilter));
if (!formatParts.length)
throw new Error("parse() requires a pattern.");
let parsedParts;
try {
parsedParts = parseParts(dateStr, formatParts);
} catch {
return invalid();
}
const now = /* @__PURE__ */ new Date();
const parsed = /* @__PURE__ */ new Map([
["YYYY", now.getFullYear()],
["MM", now.getMonth() + 1],
["DD", now.getDate()],
["HH", 0],
["mm", 0],
["ss", 0]
]);
let a = null;
let offset = "";
parsedParts.forEach((part) => {
if (part.partName === "literal")
return;
if (part.token === part.value)
return invalid();
const v = Number(part.value);
if (parsed.has(part.token)) {
parsed.set(part.token, v);
} else if (part.token === "YY") {
parsed.set("YYYY", fourDigitYear(part.value));
} else {
const t = part.token;
if (t.startsWith("d")) {
return;
} else if (t === "D") {
parsed.set("DD", v);
} else if (t === "H" || t.startsWith("h")) {
parsed.set("HH", v);
} else if (t === "M") {
parsed.set("MM", v);
} else if (t === "a" || t === "A") {
a = part.value.toLowerCase() === ap("am", locale).toLowerCase();
} else if (t === "Z" || t === "ZZ") {
offset = validOffset(part.value, t);
} else {
const values = range(t, locale, genitive);
const index = values.indexOf(part.value);
if (index !== -1) {
switch (t) {
case "MMM":
case "MMMM":
parsed.set("MM", index + 1);
break;
}
}
}
}
});
let hours = parsed.get("HH") || 0;
if (a === false) {
hours += hours === 12 ? 0 : 12;
parsed.set("HH", hours === 24 ? 0 : hours);
} else if (a === true && hours === 12) {
parsed.set("HH", 0);
}
parsed.set("MM", (parsed.get("MM") || 1) - 1);
let [Y, M, D, h, m, s] = Array.from(parsed.values());
const maxDaysInMonth = monthDays(/* @__PURE__ */ new Date(`${four(Y)}-${two(M + 1)}-10`));
if (maxDaysInMonth < D && dateOverflow === "throw")
throw new Error(`Invalid date ${four(Y)}-${two(M + 1)}-${two(D)}`);
D = dateOverflow === "backward" ? Math.min(D, maxDaysInMonth) : D;
const isoString = `${four(Y)}-${two(M + 1)}-${two(D)}T${two(h)}:${two(
m
)}:${two(s)}${offset}`;
const d = new Date(isoString);
if (isFinite(+d))
return d;
return invalid();
}
function parseParts(dateStr, formatParts) {
let i = 0;
const advance = (parts2) => [
parts2[i++],
parts2[i]
];
let pos = 0;
const parsed = [];
let n = void 0;
do {
const [current, next] = advance(formatParts);
n = next;
let len = 1;
if (current.partName === "literal") {
len = current.partValue.length;
} else if (current.partName === "timeZoneName") {
len = fixedLengthByOffset(dateStr.substring(pos));
} else if (current.token in fixedLength) {
len = fixedLength[current.token];
} else if (next) {
if (next.partName === "literal") {
len = dateStr.indexOf(next.partValue, pos) - pos;
if (len < 0)
throw new Error();
} else if (next.partName === "dayPeriod") {
for (let i2 = 1; i2 <= 4; i2++) {
if (isNaN(Number(dateStr.charAt(pos + i2)))) {
len = i2;
break;
}
}
} else {
const nextChar = dateStr.substring(pos).search(/\d/);
if (nextChar !== -1)
len = pos + nextChar;
}
} else {
len = dateStr.length;
}
parsed.push({ ...current, value: dateStr.substring(pos, pos + len) });
pos += len;
} while (n);
return parsed;
}
export {
parse,
parseParts
};
//# sourceMappingURL=parse.mjs.map
{"version":3,"sources":["../src/parse.ts"],"sourcesContent":["import { date } from \"./date\"\nimport { validate, styles, fixedLength, four, two, validOffset, fixedLengthByOffset } from \"./common\"\nimport { formatStr } from \"./formatStr\"\nimport { fourDigitYear } from \"./fourDigitYear\"\nimport { ap } from \"./ap\"\nimport { range } from \"./range\"\nimport { monthDays } from \"./monthDays\"\nimport { parts } from \"./parts\"\nimport type {\n ParseOptions,\n Format,\n Part,\n FormatStyle,\n FilledPart,\n FormatToken,\n} from \"./types\"\n\nexport function parse(options: ParseOptions): Date | never\nexport function parse(\n dateStr: string,\n format?: Format,\n locale?: string\n): Date | never\n/**\n * Parses a date string into a Date object using the given format.\n * @param dateStr - A string representing a date.\n * @param format - The format the given string is in.\n * @param locale - The locale to parse the string from.\n */\nexport function parse(\n dateStrOrOptions: string | ParseOptions,\n format: Format = \"ISO8601\",\n locale = \"device\"\n): Date | never {\n let partFilter: (part: Part) => boolean = () => true\n let dateStr: string\n let dateOverflow = \"backward\"\n if (typeof dateStrOrOptions === \"object\") {\n ;({\n date: dateStr,\n format = \"ISO8601\",\n locale = \"device\",\n dateOverflow = \"backward\",\n partFilter = () => true,\n } = dateStrOrOptions)\n } else {\n dateStr = dateStrOrOptions\n }\n if (!dateStr) throw new Error(\"parse() requires a date string.\")\n const invalid = (): never => {\n throw new Error(\n `Date (${dateStr}) does not match format (${formatStr(format, locale)})`\n )\n }\n if (format === \"ISO8601\") return date(dateStr)\n const genitive =\n styles.includes(format as FormatStyle) || typeof format === \"object\"\n const formatParts = validate(parts(format, locale).filter(partFilter))\n if (!formatParts.length) throw new Error(\"parse() requires a pattern.\")\n let parsedParts\n try {\n parsedParts = parseParts(dateStr, formatParts)\n } catch {\n return invalid()\n }\n const now = new Date()\n const parsed = new Map([\n [\"YYYY\", now.getFullYear()],\n [\"MM\", now.getMonth() + 1],\n [\"DD\", now.getDate()],\n [\"HH\", 0],\n [\"mm\", 0],\n [\"ss\", 0],\n ])\n let a: null | boolean = null\n let offset = \"\"\n parsedParts.forEach((part): void | never => {\n if (part.partName === \"literal\") return\n if (part.token === part.value) return invalid()\n const v = Number(part.value)\n if (parsed.has(part.token)) {\n // Parse for YYYY, MM, DD, HH, hh, mm, ss, Z\n parsed.set(part.token, v)\n } else if (part.token === \"YY\") {\n // Parse for YY\n parsed.set(\"YYYY\", fourDigitYear(part.value))\n } else {\n /* MMM - Short name Jan-Dec\n * MMMM - Full name January - December\n * h - Minimum hour digits, 12 hour clock, 1-12\n * hh - 2 hour digits, 12 hour clock, 01-12\n * m - The minute 0-59\n * mm - The minute 00-12\n * s - The second 0-59\n * a - am/pm\n * A - AM/PM\n */\n const t = part.token\n if (t.startsWith(\"d\")) {\n // d, ddd, dddd — we just ignore these because they are non specific\n return\n } else if (t === \"D\") {\n parsed.set(\"DD\", v)\n } else if (t === \"H\" || t.startsWith(\"h\")) {\n parsed.set(\"HH\", v)\n } else if (t === \"M\") {\n parsed.set(\"MM\", v)\n } else if (t === \"a\" || t === \"A\") {\n a = part.value.toLowerCase() === ap(\"am\", locale).toLowerCase()\n } else if (t === \"Z\" || t === \"ZZ\") {\n offset = validOffset(part.value, t)\n } else {\n const values = range(t as FormatToken, locale, genitive)\n const index = values.indexOf(part.value)\n if (index !== -1) {\n switch (t) {\n case \"MMM\":\n case \"MMMM\":\n parsed.set(\"MM\", index + 1)\n break\n }\n }\n }\n }\n })\n let hours = parsed.get(\"HH\") || 0\n if (a === false) {\n hours += hours === 12 ? 0 : 12\n parsed.set(\"HH\", hours === 24 ? 0 : hours)\n } else if (a === true && hours === 12) {\n // 12am === 00 in 24 hour clock.\n parsed.set(\"HH\", 0)\n }\n parsed.set(\"MM\", (parsed.get(\"MM\") || 1) - 1)\n // eslint-disable-next-line prefer-const\n let [Y, M, D, h, m, s] = Array.from(parsed.values())\n\n // Determine if the date is valid for the month.\n const maxDaysInMonth = monthDays(new Date(`${four(Y)}-${two(M + 1)}-10`))\n if (maxDaysInMonth < D && dateOverflow === \"throw\")\n throw new Error(`Invalid date ${four(Y)}-${two(M + 1)}-${two(D)}`)\n D = dateOverflow === \"backward\" ? Math.min(D, maxDaysInMonth) : D\n\n // Create the date.\n const isoString = `${four(Y)}-${two(M + 1)}-${two(D)}T${two(h)}:${two(\n m\n )}:${two(s)}${offset}`\n const d = new Date(isoString)\n if (isFinite(+d)) return d\n return invalid()\n}\n\n/**\n * Given a string date and corresponding format parts, fill the parts with the\n * data from the string.\n * @param dateStr - A string to parse.\n * @param formatParts - The expected parts of the given string.\n */\nexport function parseParts(dateStr: string, formatParts: Part[]): FilledPart[] {\n let i = 0\n const advance = (parts: Part[]): [Part, Part | undefined] => [\n parts[i++],\n parts[i],\n ]\n let pos = 0\n const parsed: FilledPart[] = []\n let n: undefined | Part = undefined\n do {\n const [current, next] = advance(formatParts)\n n = next\n let len = 1\n if (current.partName === \"literal\") {\n // Literals can be discarded\n len = current.partValue.length\n } else if (current.partName === \"timeZoneName\") {\n len = fixedLengthByOffset(dateStr.substring(pos))\n } else if (current.token in fixedLength) {\n // Fixed length parse\n len = fixedLength[current.token as keyof typeof fixedLength]\n } else if (next) {\n // Variable length parse.\n if (next.partName === \"literal\") {\n len = dateStr.indexOf(next.partValue, pos) - pos\n if (len < 0) throw new Error()\n } else if (next.partName === \"dayPeriod\") {\n // Our validator is ensuring that the current item must be a variable\n // length number. We need to extract it.\n for (let i = 1; i <= 4; i++) {\n if (isNaN(Number(dateStr.charAt(pos + i)))) {\n len = i\n break\n }\n }\n } else {\n // Our validator guarantees the next is either not a number or it\n // will be the end of the string\n const nextChar = dateStr.substring(pos).search(/\\d/)\n if (nextChar !== -1) len = pos + nextChar\n }\n } else {\n len = dateStr.length\n }\n\n parsed.push({ ...current, value: dateStr.substring(pos, pos + len) })\n pos += len\n } while (n)\n return parsed\n}\n"],"mappings":";AAAA,SAAS,YAAY;AACrB,SAAS,UAAU,QAAQ,aAAa,MAAM,KAAK,aAAa,2BAA2B;AAC3F,SAAS,iBAAiB;AAC1B,SAAS,qBAAqB;AAC9B,SAAS,UAAU;AACnB,SAAS,aAAa;AACtB,SAAS,iBAAiB;AAC1B,SAAS,aAAa;AAsBf,SAAS,MACd,kBACA,SAAiB,W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,IAC7D,WAAW,MAAM;AAEf,UAAI,KAAK,aAAa,WAAW;AAC/B,cAAM,QAAQ,QAAQ,KAAK,WAAW,GAAG,IAAI;AAC7C,YAAI,MAAM;AAAG,gBAAM,IAAI,MAAM;AAAA,MAC/B,WAAW,KAAK,aAAa,aAAa;AAGxC,iBAASC,KAAI,GAAGA,MAAK,GAAGA,MAAK;AAC3B,cAAI,MAAM,OAAO,QAAQ,OAAO,MAAMA,EAAC,CAAC,CAAC,GAAG;AAC1C,kBAAMA;AACN;AAAA,UACF;AAAA,QACF;AAAA,MACF,OAAO;AAGL,cAAM,WAAW,QAAQ,UAAU,GAAG,EAAE,OAAO,IAAI;AACnD,YAAI,aAAa;AAAI,gBAAM,MAAM;AAAA,MACnC;AAAA,IACF,OAAO;AACL,YAAM,QAAQ;AAAA,IAChB;AAEA,WAAO,KAAK,EAAE,GAAG,SAAS,OAAO,QAAQ,UAAU,KAAK,MAAM,GAAG,EAAE,CAAC;AACpE,WAAO;AAAA,EACT,SAAS;AACT,SAAO;AACT;","names":["parts","i"]}
import { Format, Part } from './types.js';
/**
* Given a format string, produce an array of matching "parts", each part
* contains a regular expression and the corresponding
* Intl.DateTimeFormatPartTypesRegistry key/value.
* @param format - A format string like MM/DD/YYYY
* @param locale - The locale to parse for.
*/
declare function parts(format: Format, locale: string): Part[];
export { parts };
// src/parts.ts
import {
styles,
normStr,
tokens,
memoParts,
clockAgnostic,
clock24,
specDate,
clock12
} from "./common.mjs";
function parts(format, locale) {
if (styles.includes(format) || typeof format === "object") {
return styleParts(format, locale);
}
let f = format;
let match = 0;
const testPattern = (pattern) => {
if (!pattern[2])
pattern[2] = new RegExp(`(.)?(${pattern[0]})`, "g");
if (pattern[2].test(f)) {
let didAdd = 0;
f = f.replace(pattern[2], (_, prefix, actualMatch) => {
if (prefix === "\\")
return actualMatch;
return `${typeof prefix === "string" ? prefix : ""}{!${didAdd++ ? match : match++}!}`;
});
return !!didAdd;
}
return false;
};
function validate(patterns) {
const parts3 = patterns.map((part) => part.partName);
const deduped = new Set(parts3);
if (parts3.length > deduped.size) {
throw new Error(`Cannot reuse format tokens.`);
}
return patterns;
}
function createPart(hour12, [token, option, exp]) {
const partName = Object.keys(option)[0];
const partValue = option[partName];
return {
option,
partName,
partValue,
token,
pattern: exp,
hour12
};
}
const found24Patterns = clockAgnostic.filter(testPattern).concat(clock24.filter(testPattern)).map(createPart.bind(null, false));
const parts2 = validate(
found24Patterns.concat(
clock12.filter(testPattern).map(createPart.bind(null, true))
)
);
const extractIndex = /^\{!(\d+)!\}$/;
return f.split(/(\{!\d+!\})/).map((match2) => {
const hasIndex = match2.match(extractIndex);
if (hasIndex) {
return parts2[Number(hasIndex[1])];
}
return {
option: { literal: match2 },
partName: "literal",
partValue: match2,
token: match2,
pattern: new RegExp(""),
hour12: false
};
}).filter((part) => !(part.partName === "literal" && part.partValue === ""));
}
function styleParts(format, locale) {
const options = {
timeZone: "UTC"
};
if (typeof format === "string") {
options.dateStyle = format;
} else {
if ("date" in format)
options.dateStyle = format.date;
if ("time" in format)
options.timeStyle = format.time;
}
const formatter = new Intl.DateTimeFormat(locale, options);
const segments = formatter.formatToParts(new Date(specDate)).map(normStr);
const hourTypeSegments = formatter.formatToParts(/* @__PURE__ */ new Date("1999-04-05T23:05:01.000Z")).map(normStr);
const hourPart = hourTypeSegments.find((segment) => segment.type === "hour");
const hourType = hourPart && hourPart.value === "23" ? 24 : 12;
return segments.map((part) => {
const partName = part.type;
const formatPattern = guessPattern(
part.type,
part.value,
locale,
part.type === "hour" ? hourType : void 0,
options
);
if (formatPattern === void 0)
return;
const partValue = formatPattern[1][partName];
if (!partValue)
return;
if (!formatPattern[2])
formatPattern[2] = new RegExp(`${formatPattern[0]}`, "g");
return {
option: { [partName]: partValue },
partName,
partValue,
token: formatPattern[0],
pattern: formatPattern[2],
hour12: hourType === 12
};
}).filter((part) => !!part);
}
function guessPattern(partName, partValue, locale, hour, options) {
const l = partValue.length;
const n = !isNaN(Number(partValue));
let style;
switch (partName) {
case "year":
return l === 2 ? tokens.get("YY") : tokens.get("YYYY");
case "month":
if (n)
return l === 1 ? tokens.get("M") : tokens.get("MM");
style = partStyle(locale, partName, partValue);
switch (style) {
case "long":
return tokens.get("MMMM");
default:
return tokens.get("MMM");
}
case "day":
return l === 1 ? tokens.get("D") : tokens.get("DD");
case "weekday":
style = partStyle(locale, partName, partValue);
switch (style) {
case "narrow":
return tokens.get("d");
case "short":
return tokens.get("ddd");
default:
return tokens.get("dddd");
}
case "hour":
if (hour === 12)
return l === 1 ? tokens.get("h") : tokens.get("hh");
return l === 1 ? tokens.get("H") : tokens.get("HH");
case "minute":
return l === 1 ? tokens.get("m") : tokens.get("mm");
case "second":
return l === 1 ? tokens.get("s") : tokens.get("ss");
case "dayPeriod":
return /^[A-Z]+$/u.test(partValue) ? tokens.get("A") : tokens.get("a");
case "literal":
return [partValue, { literal: partValue }, new RegExp("")];
case "timeZoneName":
return options.timeStyle === "full" ? tokens.get("Z") : tokens.get("ZZ");
default:
return void 0;
}
}
function partStyle(locale, part, value) {
if (!memoParts.has(locale)) {
const date = new Date(specDate);
const weekdays = [3, 8, 9, 7, 6, 4, 3];
const parts2 = ["weekday", "month", "dayPeriod"];
const partStyles = ["long", "short", "narrow"];
const formats2 = {};
for (let i = 0; i < 12; i++) {
date.setMonth(0 + i);
if (i in weekdays)
date.setDate(weekdays[i]);
date.setUTCHours(8 + i);
for (const style of partStyles) {
const segments = new Intl.DateTimeFormat(
locale,
parts2.reduce(
(options, part2) => Object.assign(options, { [part2]: style }),
{ hour12: true, timeZone: "UTC" }
)
).formatToParts(date).map(normStr);
if (style === "long" || style === "short") {
const genitiveFormattedParts = new Intl.DateTimeFormat(locale, {
dateStyle: style === "short" ? "medium" : "long",
timeZone: "UTC"
}).formatToParts(date).map(normStr);
const genitiveMonth = genitiveFormattedParts.find(
(part2) => part2.type === "month"
);
const index = segments.findIndex((part2) => part2.type === "month");
if (index > -1 && genitiveMonth)
segments[index] = genitiveMonth;
}
segments.forEach((part2) => {
if (part2.type === "literal")
return;
const type = part2.type;
formats2[type] = Object.assign(formats2[type] || {}, {
[part2.value]: style
});
});
}
}
memoParts.set(locale, formats2);
}
const formats = memoParts.get(locale);
return formats ? formats[part][value] : void 0;
}
export {
parts
};
//# sourceMappingURL=parts.mjs.map
{"version":3,"sources":["../src/parts.ts"],"sourcesContent":["import {\n styles,\n normStr,\n tokens,\n memoParts,\n clockAgnostic,\n clock24,\n specDate,\n clock12,\n} from \"./common\"\nimport type {\n ParseOptions,\n Format,\n Part,\n FormatStyle,\n FormatStyleObj,\n FormatPattern,\n NamedFormats,\n NamedFormatOption,\n} from \"./types\"\n/**\n * Given a format string, produce an array of matching \"parts\", each part\n * contains a regular expression and the corresponding\n * Intl.DateTimeFormatPartTypesRegistry key/value.\n * @param format - A format string like MM/DD/YYYY\n * @param locale - The locale to parse for.\n */\nexport function parts(format: Format, locale: string): Part[] {\n if (styles.includes(format as FormatStyle) || typeof format === \"object\") {\n return styleParts(format as FormatStyle | FormatStyleObj, locale)\n }\n let f = format\n let match = 0\n const testPattern = (pattern: FormatPattern) => {\n if (!pattern[2]) pattern[2] = new RegExp(`(.)?(${pattern[0]})`, \"g\")\n if (pattern[2].test(f)) {\n let didAdd = 0\n f = f.replace(pattern[2], (_, prefix, actualMatch) => {\n if (prefix === \"\\\\\") return actualMatch\n return `${typeof prefix === \"string\" ? prefix : \"\"}{!${\n didAdd++ ? match : match++\n }!}`\n })\n return !!didAdd\n }\n return false\n }\n\n function validate(patterns: Part[]): Part[] {\n const parts = patterns.map((part) => part.partName)\n const deduped = new Set(parts)\n if (parts.length > deduped.size) {\n throw new Error(`Cannot reuse format tokens.`)\n }\n return patterns\n }\n\n function createPart(\n hour12: boolean,\n [token, option, exp]: FormatPattern\n ): Part {\n const partName = Object.keys(option)[0] as Intl.DateTimeFormatPartTypes\n const partValue = option[partName] as string\n return {\n option,\n partName,\n partValue,\n token,\n pattern: exp as RegExp,\n hour12,\n }\n }\n\n const found24Patterns = clockAgnostic\n .filter(testPattern)\n .concat(clock24.filter(testPattern))\n .map(createPart.bind(null, false))\n\n // Reset the format before re-checking\n const parts = validate(\n found24Patterns.concat(\n clock12.filter(testPattern).map(createPart.bind(null, true))\n )\n )\n const extractIndex = /^\\{!(\\d+)!\\}$/\n return f\n .split(/(\\{!\\d+!\\})/)\n .map((match: string): Part => {\n const hasIndex = match.match(extractIndex)\n if (hasIndex) {\n return parts[Number(hasIndex[1])]\n }\n return {\n option: { literal: match },\n partName: \"literal\",\n partValue: match,\n token: match,\n pattern: new RegExp(\"\"),\n hour12: false,\n }\n })\n .filter((part) => !(part.partName === \"literal\" && part.partValue === \"\"))\n}\n\n/**\n * Determines the parts in a native date style, like \"full\".\n * @param format - A date style like \"full\" or \"short\"\n * @param locale - The locale string\n */\nfunction styleParts(\n format: FormatStyle | FormatStyleObj,\n locale: string\n): Part[] {\n const options: Intl.DateTimeFormatOptions = {\n timeZone: \"UTC\",\n }\n if (typeof format === \"string\") {\n options.dateStyle = format\n } else {\n if (\"date\" in format) options.dateStyle = format.date\n if (\"time\" in format) options.timeStyle = format.time\n }\n\n const formatter = new Intl.DateTimeFormat(locale, options)\n const segments = formatter.formatToParts(new Date(specDate)).map(normStr)\n const hourTypeSegments = formatter\n .formatToParts(new Date(\"1999-04-05T23:05:01.000Z\"))\n .map(normStr)\n const hourPart = hourTypeSegments.find((segment) => segment.type === \"hour\")\n const hourType = hourPart && hourPart.value === \"23\" ? 24 : 12\n return segments\n .map((part): Part | undefined => {\n const partName = part.type\n const formatPattern = guessPattern(\n part.type,\n part.value,\n locale,\n part.type === \"hour\" ? hourType : undefined,\n options\n )\n if (formatPattern === undefined) return\n const partValue = formatPattern[1][partName]\n if (!partValue) return\n if (!formatPattern[2])\n formatPattern[2] = new RegExp(`${formatPattern[0]}`, \"g\")\n return {\n option: { [partName]: partValue },\n partName,\n partValue,\n token: formatPattern[0],\n pattern: formatPattern[2],\n hour12: hourType === 12,\n }\n })\n .filter((part): part is Part => !!part)\n}\n\n/**\n * Attempts to guess the correct part value type for a given dateStyle. For\n * example a month of 02 would be \"2-digit\".\n *\n * @param partName - The part name to guess for, like 'year' or 'month'\n * @param partValue - The current value, it is assumed this is the smallest denom.\n */\nfunction guessPattern<T extends Intl.DateTimeFormatPartTypes>(\n partName: T,\n partValue: string,\n locale: string,\n hour: T extends \"hour\" ? 12 | 24 : undefined,\n options: Intl.DateTimeFormatOptions\n): FormatPattern | undefined {\n const l = partValue.length\n const n = !isNaN(Number(partValue))\n let style: NamedFormatOption | undefined\n /* eslint-disable @typescript-eslint/no-non-null-assertion */\n switch (partName) {\n case \"year\":\n return l === 2 ? tokens.get(\"YY\") : tokens.get(\"YYYY\")\n case \"month\":\n if (n) return l === 1 ? tokens.get(\"M\") : tokens.get(\"MM\")\n style = partStyle(locale, partName, partValue)\n switch (style) {\n case \"long\":\n return tokens.get(\"MMMM\")\n default:\n return tokens.get(\"MMM\")\n }\n case \"day\":\n return l === 1 ? tokens.get(\"D\") : tokens.get(\"DD\")\n case \"weekday\":\n style = partStyle(locale, partName, partValue)\n switch (style) {\n case \"narrow\":\n return tokens.get(\"d\")\n case \"short\":\n return tokens.get(\"ddd\")\n default:\n return tokens.get(\"dddd\")\n }\n case \"hour\":\n // Need to distinguish the locale’s default as 24 or 12 hour.\n if (hour === 12) return l === 1 ? tokens.get(\"h\") : tokens.get(\"hh\")\n return l === 1 ? tokens.get(\"H\") : tokens.get(\"HH\")\n case \"minute\":\n return l === 1 ? tokens.get(\"m\") : tokens.get(\"mm\")\n case \"second\":\n return l === 1 ? tokens.get(\"s\") : tokens.get(\"ss\")\n case \"dayPeriod\":\n return /^[A-Z]+$/u.test(partValue) ? tokens.get(\"A\") : tokens.get(\"a\")\n case \"literal\":\n return [partValue, { literal: partValue }, new RegExp(\"\")]\n case \"timeZoneName\":\n return options.timeStyle === \"full\" ? tokens.get(\"Z\") : tokens.get(\"ZZ\")\n default:\n return undefined\n }\n /* eslint-enable @typescript-eslint/no-non-null-assertion */\n}\n\n/**\n * Determines what \"style\" a given part is in. For example, if you provide:\n * ```js\n * partStyle('en', 'month', 'Jan')\n * // returns \"short\".\n * ```\n * Part styles are always expected to be \"genitive\" — for use in \"dateStyle\".\n * @param locale - Locale string\n * @param part - The part to attempt a lookup on\n * @param value - The value of a given part.\n */\nfunction partStyle(\n locale: string,\n part: keyof NamedFormats,\n value: string\n): NamedFormatOption | undefined {\n if (!memoParts.has(locale)) {\n const date = new Date(specDate)\n const weekdays = [3, 8, 9, 7, 6, 4, 3]\n const parts = [\"weekday\", \"month\", \"dayPeriod\"]\n const partStyles: NamedFormatOption[] = [\"long\", \"short\", \"narrow\"]\n const formats: Partial<NamedFormats> = {}\n for (let i = 0; i < 12; i++) {\n date.setMonth(0 + i)\n if (i in weekdays) date.setDate(weekdays[i])\n date.setUTCHours(8 + i)\n for (const style of partStyles) {\n const segments = new Intl.DateTimeFormat(\n locale,\n parts.reduce(\n (options, part) => Object.assign(options, { [part]: style }),\n { hour12: true, timeZone: \"UTC\" }\n )\n )\n .formatToParts(date)\n .map(normStr)\n if (style === \"long\" || style === \"short\") {\n const genitiveFormattedParts = new Intl.DateTimeFormat(locale, {\n dateStyle: style === \"short\" ? \"medium\" : \"long\",\n timeZone: \"UTC\",\n })\n .formatToParts(date)\n .map(normStr)\n const genitiveMonth = genitiveFormattedParts.find(\n (part) => part.type === \"month\"\n )\n const index = segments.findIndex((part) => part.type === \"month\")\n if (index > -1 && genitiveMonth) segments[index] = genitiveMonth\n }\n segments.forEach((part) => {\n if (part.type === \"literal\") return\n const type = part.type as keyof NamedFormats\n formats[type] = Object.assign(formats[type] || {}, {\n [part.value]: style,\n })\n })\n }\n }\n memoParts.set(locale, formats as NamedFormats)\n }\n const formats = memoParts.get(locale)\n return formats ? formats[part][value] : undefined\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAkBA,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KAAK;AAAA,UACxB;AAAA,UACAF,OAAM;AAAA,YACJ,CAAC,SAASG,UAAS,OAAO,OAAO,SAAS,EAAE,CAACA,KAAI,GAAG,MAAM,CAAC;AAAA,YAC3D,EAAE,QAAQ,MAAM,UAAU,MAAM;AAAA,UAClC;AAAA,QACF,EACG,cAAc,IAAI,EAClB,IAAI,OAAO;AACd,YAAI,UAAU,UAAU,UAAU,SAAS;AACzC,gBAAM,yBAAyB,IAAI,KAAK,eAAe,QAAQ;AAAA,YAC7D,WAAW,UAAU,UAAU,WAAW;AAAA,YAC1C,UAAU;AAAA,UACZ,CAAC,EACE,cAAc,IAAI,EAClB,IAAI,OAAO;AACd,gBAAM,gBAAgB,uBAAuB;AAAA,YAC3C,CAACA,UAASA,MAAK,SAAS;AAAA,UAC1B;AACA,gBAAM,QAAQ,SAAS,UAAU,CAACA,UAASA,MAAK,SAAS,OAAO;AAChE,cAAI,QAAQ,MAAM;AAAe,qBAAS,KAAK,IAAI;AAAA,QACrD;AACA,iBAAS,QAAQ,CAACA,UAAS;AACzB,cAAIA,MAAK,SAAS;AAAW;AAC7B,gBAAM,OAAOA,MAAK;AAClB,UAAAD,SAAQ,IAAI,IAAI,OAAO,OAAOA,SAAQ,IAAI,KAAK,CAAC,GAAG;AAAA,YACjD,CAACC,MAAK,KAAK,GAAG;AAAA,UAChB,CAAC;AAAA,QACH,CAAC;AAAA,MACH;AAAA,IACF;AACA,cAAU,IAAI,QAAQD,QAAuB;AAAA,EAC/C;AACA,QAAM,UAAU,UAAU,IAAI,MAAM;AACpC,SAAO,UAAU,QAAQ,IAAI,EAAE,KAAK,IAAI;AAC1C;","names":["parts","match","formats","part"]}
import { FormatToken } from './types.js';
/**
* Returns an array of options for a given token in a given locale.
* @param token - Get the full range of options for a given token
* @param locale - The locale to fetch the options for.
*/
declare function range(token: FormatToken, locale?: string, genitive?: boolean): string[];
export { range };
// src/range.ts
import { format } from "./format.mjs";
import { ap } from "./ap.mjs";
function range(token, locale = "en", genitive = false) {
const r = (n, c) => Array(n).fill("").map((_, i) => `${c(i)}`);
if (token === "M")
return r(12, (i) => i + 1);
if (token === "MM")
return r(12, (i) => {
const m = i + 1;
return m < 10 ? `0${m}` : m;
});
if (token.startsWith("M"))
return range("MM").map(
(m) => format(`2000-${m}-05`, token, locale, genitive)
);
if (token.startsWith("d"))
return r(7, (i) => `0${i + 2}`).map(
(d) => format(`2022-10-${d}`, token, locale)
);
if (token === "a")
return [ap("am", locale).toLowerCase(), ap("pm", locale).toLowerCase()];
if (token === "A")
return [ap("am", locale).toUpperCase(), ap("pm", locale).toUpperCase()];
if (token.startsWith("Y")) {
const year = (/* @__PURE__ */ new Date()).getFullYear();
return r(120, (i) => i + 1).reduce(
(ranges, i) => {
if (i !== "120")
ranges.push(format(`${year + Number(i)}-06-06`, token, locale));
ranges.unshift(format(`${year - Number(i)}-06-06`, token, locale));
return ranges;
},
[format(`${year}-06-06`, token, locale)]
);
}
if (token.startsWith("D"))
return r(31, (i) => `${token === "DD" && i < 9 ? "0" : ""}${i + 1}`);
if (token.startsWith("H"))
return r(24, (i) => `${token === "HH" && i < 10 ? "0" : ""}${i}`);
if (token.startsWith("h"))
return r(12, (i) => `${token === "hh" && i < 9 ? "0" : ""}${i + 1}`);
if (token.startsWith("m") || token.startsWith("s"))
return r(60, (i) => `${token.length > 1 && i < 10 ? "0" : ""}${i}`);
return [];
}
export {
range
};
//# sourceMappingURL=range.mjs.map
{"version":3,"sources":["../src/range.ts"],"sourcesContent":["import { format } from \"./format\"\nimport { ap } from \"./ap\"\nimport type { FormatToken } from \"./types\"\n/**\n * Returns an array of options for a given token in a given locale.\n * @param token - Get the full range of options for a given token\n * @param locale - The locale to fetch the options for.\n */\nexport function range(\n token: FormatToken,\n locale = \"en\",\n genitive = false\n): string[] {\n const r: (n: number, c: (index: number) => string | number) => string[] = (\n n,\n c\n ) =>\n Array(n)\n .fill(\"\")\n .map((_, i) => `${c(i)}`)\n\n if (token === \"M\") return r(12, (i) => i + 1)\n if (token === \"MM\")\n return r(12, (i) => {\n const m = i + 1\n return m < 10 ? `0${m}` : m\n })\n // MMM and MMMM\n if (token.startsWith(\"M\"))\n return range(\"MM\").map((m) =>\n format(`2000-${m}-05`, token, locale, genitive)\n )\n if (token.startsWith(\"d\"))\n return r(7, (i) => `0${i + 2}`).map((d) =>\n format(`2022-10-${d}`, token, locale)\n )\n if (token === \"a\")\n return [ap(\"am\", locale).toLowerCase(), ap(\"pm\", locale).toLowerCase()]\n if (token === \"A\")\n return [ap(\"am\", locale).toUpperCase(), ap(\"pm\", locale).toUpperCase()]\n if (token.startsWith(\"Y\")) {\n const year = new Date().getFullYear()\n return r(120, (i) => i + 1).reduce(\n (ranges, i) => {\n if (i !== \"120\")\n ranges.push(format(`${year + Number(i)}-06-06`, token, locale))\n ranges.unshift(format(`${year - Number(i)}-06-06`, token, locale))\n return ranges\n },\n [format(`${year}-06-06`, token, locale)]\n )\n }\n if (token.startsWith(\"D\"))\n return r(31, (i) => `${token === \"DD\" && i < 9 ? \"0\" : \"\"}${i + 1}`)\n if (token.startsWith(\"H\"))\n return r(24, (i) => `${token === \"HH\" && i < 10 ? \"0\" : \"\"}${i}`)\n if (token.startsWith(\"h\"))\n return r(12, (i) => `${token === \"hh\" && i < 9 ? \"0\" : \"\"}${i + 1}`)\n if (token.startsWith(\"m\") || token.startsWith(\"s\"))\n return r(60, (i) => `${token.length > 1 && i < 10 ? \"0\" : \"\"}${i}`)\n return []\n}\n"],"mappings":";AAAA,SAAS,cAAc;AACvB,SAAS,UAAU;AAOZ,SAAS,MACd,OACA,SAAS,MACT,WAAW,OACD;AACV,QAAM,IAAoE,CACxE,GACA,MAEA,MAAM,CAAC,EACJ,KAAK,EAAE,EACP,IAAI,CAAC,GAAG,MAAM,GAAG,EAAE,CAAC,CAAC,EAAE;AAE5B,MAAI,UAAU;AAAK,WAAO,EAAE,IAAI,CAAC,MAAM,IAAI,CAAC;AAC5C,MAAI,UAAU;AACZ,WAAO,EAAE,IAAI,CAAC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AO,EAAE,IAAI,CAAC,MAAM,GAAG,UAAU,QAAQ,IAAI,KAAK,MAAM,EAAE,GAAG,CAAC,EAAE;AAClE,MAAI,MAAM,WAAW,GAAG;AACtB,WAAO,EAAE,IAAI,CAAC,MAAM,GAAG,UAAU,QAAQ,IAAI,IAAI,MAAM,EAAE,GAAG,IAAI,CAAC,EAAE;AACrE,MAAI,MAAM,WAAW,GAAG,KAAK,MAAM,WAAW,GAAG;AAC/C,WAAO,EAAE,IAAI,CAAC,MAAM,GAAG,MAAM,SAAS,KAAK,IAAI,KAAK,MAAM,EAAE,GAAG,CAAC,EAAE;AACpE,SAAO,CAAC;AACV;","names":[]}
import { DateInput } from './types.js';
/**
* Inverts the offset and applies it to the given date, returning a new date.
* @param dateInput - The date to remove the offset from.
* @param offset - The offset to remove in the +-HHmm or +-HH:mm format.
*/
declare function removeOffset(dateInput: DateInput, offset?: string): Date;
export { removeOffset };
// src/removeOffset.ts
import { applyOffset } from "./applyOffset.mjs";
function removeOffset(dateInput, offset = "+00:00") {
const positive = offset.slice(0, 1) === "+";
return applyOffset(
dateInput,
offset.replace(positive ? "+" : "-", positive ? "-" : "+")
);
}
export {
removeOffset
};
//# sourceMappingURL=removeOffset.mjs.map
{"version":3,"sources":["../src/removeOffset.ts"],"sourcesContent":["import { applyOffset } from \"./applyOffset\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Inverts the offset and applies it to the given date, returning a new date.\n * @param dateInput - The date to remove the offset from.\n * @param offset - The offset to remove in the +-HHmm or +-HH:mm format.\n */\nexport function removeOffset(dateInput: DateInput, offset = \"+00:00\"): Date {\n const positive = offset.slice(0, 1) === \"+\"\n return applyOffset(\n dateInput,\n offset.replace(positive ? \"+\" : \"-\", positive ? \"-\" : \"+\")\n )\n}\n"],"mappings":";AAAA,SAAS,mBAAmB;AAQrB,SAAS,aAAa,WAAsB,SAAS,UAAgB;AAC1E,QAAM,WAAW,OAAO,MAAM,GAAG,CAAC,MAAM;AACxC,SAAO;AAAA,IACL;AAAA,IACA,OAAO,QAAQ,WAAW,MAAM,KAAK,WAAW,MAAM,GAAG;AAAA,EAC3D;AACF;","names":[]}
import { DateInput } from './types.js';
/**
* Checks if two date objects refer to the same date. Ignores time.
* @param inputDateA - First date to compare
* @param inputDateB - Second date to compare
*/
declare function sameDay(inputDateA: DateInput, inputDateB: DateInput): boolean;
export { sameDay };
// src/sameDay.ts
import { date } from "./date.mjs";
function sameDay(inputDateA, inputDateB) {
const a = date(inputDateA);
const b = date(inputDateB);
return a.getDate() === b.getDate() && a.getMonth() === b.getMonth() && a.getFullYear() === b.getFullYear();
}
export {
sameDay
};
//# sourceMappingURL=sameDay.mjs.map
{"version":3,"sources":["../src/sameDay.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Checks if two date objects refer to the same date. Ignores time.\n * @param inputDateA - First date to compare\n * @param inputDateB - Second date to compare\n */\nexport function sameDay(inputDateA: DateInput, inputDateB: DateInput) {\n const a = date(inputDateA)\n const b = date(inputDateB)\n return (\n a.getDate() === b.getDate() &&\n a.getMonth() === b.getMonth() &&\n a.getFullYear() === b.getFullYear()\n )\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAQd,SAAS,QAAQ,YAAuB,YAAuB;AACpE,QAAM,IAAI,KAAK,UAAU;AACzB,QAAM,IAAI,KAAK,UAAU;AACzB,SACE,EAAE,QAAQ,MAAM,EAAE,QAAQ,KAC1B,EAAE,SAAS,MAAM,EAAE,SAAS,KAC5B,EAAE,YAAY,MAAM,EAAE,YAAY;AAEtC;","names":[]}
import { DateInput } from './types.js';
/**
* Checks if two date objects refer to the same time hour. Ignores date.
* @param inputDateA - First date to compare
* @param inputDateB - Second date to compare
*/
declare function sameHour(inputDateA: DateInput, inputDateB: DateInput): boolean;
export { sameHour };
// src/sameHour.ts
import { date } from "./date.mjs";
function sameHour(inputDateA, inputDateB) {
const a = date(inputDateA);
const b = date(inputDateB);
return a.getHours() === b.getHours();
}
export {
sameHour
};
//# sourceMappingURL=sameHour.mjs.map
{"version":3,"sources":["../src/sameHour.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Checks if two date objects refer to the same time hour. Ignores date.\n * @param inputDateA - First date to compare\n * @param inputDateB - Second date to compare\n */\nexport function sameHour(inputDateA: DateInput, inputDateB: DateInput) {\n const a = date(inputDateA)\n const b = date(inputDateB)\n return a.getHours() === b.getHours()\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAQd,SAAS,SAAS,YAAuB,YAAuB;AACrE,QAAM,IAAI,KAAK,UAAU;AACzB,QAAM,IAAI,KAAK,UAAU;AACzB,SAAO,EAAE,SAAS,MAAM,EAAE,SAAS;AACrC;","names":[]}
import { DateInput } from './types.js';
/**
* Checks if two date objects refer to the same time minutes. Ignores date.
* @param inputDateA - First date to compare
* @param inputDateB - Second date to compare
*/
declare function sameMinute(inputDateA: DateInput, inputDateB: DateInput): boolean;
export { sameMinute };
// src/sameMinute.ts
import { date } from "./date.mjs";
function sameMinute(inputDateA, inputDateB) {
const a = date(inputDateA);
const b = date(inputDateB);
return a.getMinutes() === b.getMinutes();
}
export {
sameMinute
};
//# sourceMappingURL=sameMinute.mjs.map
{"version":3,"sources":["../src/sameMinute.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Checks if two date objects refer to the same time minutes. Ignores date.\n * @param inputDateA - First date to compare\n * @param inputDateB - Second date to compare\n */\nexport function sameMinute(inputDateA: DateInput, inputDateB: DateInput) {\n const a = date(inputDateA)\n const b = date(inputDateB)\n return a.getMinutes() === b.getMinutes()\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAQd,SAAS,WAAW,YAAuB,YAAuB;AACvE,QAAM,IAAI,KAAK,UAAU;AACzB,QAAM,IAAI,KAAK,UAAU;AACzB,SAAO,EAAE,WAAW,MAAM,EAAE,WAAW;AACzC;","names":[]}
import { DateInput } from './types.js';
/**
* Checks if two date objects refer to the same time seconds. Ignores date.
* @param inputDateA - First date to compare
* @param inputDateB - Second date to compare
*/
declare function sameSecond(inputDateA: DateInput, inputDateB: DateInput): boolean;
export { sameSecond };
// src/sameSecond.ts
import { date } from "./date.mjs";
function sameSecond(inputDateA, inputDateB) {
const a = date(inputDateA);
const b = date(inputDateB);
return a.getSeconds() === b.getSeconds();
}
export {
sameSecond
};
//# sourceMappingURL=sameSecond.mjs.map
{"version":3,"sources":["../src/sameSecond.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Checks if two date objects refer to the same time seconds. Ignores date.\n * @param inputDateA - First date to compare\n * @param inputDateB - Second date to compare\n */\nexport function sameSecond(inputDateA: DateInput, inputDateB: DateInput) {\n const a = date(inputDateA)\n const b = date(inputDateB)\n return a.getSeconds() === b.getSeconds()\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAQd,SAAS,WAAW,YAAuB,YAAuB;AACvE,QAAM,IAAI,KAAK,UAAU;AACzB,QAAM,IAAI,KAAK,UAAU;AACzB,SAAO,EAAE,WAAW,MAAM,EAAE,WAAW;AACzC;","names":[]}
import { DateInput } from './types.js';
/**
* Checks if two date objects refer to the same year.
* @param inputDateA - First date to compare
* @param inputDateB - Second date to compare
*/
declare function sameYear(inputDateA: DateInput, inputDateB: DateInput): boolean;
export { sameYear };
// src/sameYear.ts
import { date } from "./date.mjs";
function sameYear(inputDateA, inputDateB) {
const a = date(inputDateA);
const b = date(inputDateB);
return a.getFullYear() === b.getFullYear();
}
export {
sameYear
};
//# sourceMappingURL=sameYear.mjs.map
{"version":3,"sources":["../src/sameYear.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Checks if two date objects refer to the same year.\n * @param inputDateA - First date to compare\n * @param inputDateB - Second date to compare\n */\nexport function sameYear(inputDateA: DateInput, inputDateB: DateInput) {\n const a = date(inputDateA)\n const b = date(inputDateB)\n return a.getFullYear() === b.getFullYear()\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAQd,SAAS,SAAS,YAAuB,YAAuB;AACrE,QAAM,IAAI,KAAK,UAAU;AACzB,QAAM,IAAI,KAAK,UAAU;AACzB,SAAO,EAAE,YAAY,MAAM,EAAE,YAAY;AAC3C;","names":[]}
/**
* The date format used as an input value. Either a date or an ISO8601 string.
*/
type DateInput = Date | string;
/**
* Format parts with text names use these descriptors:
*/
type NamedFormatOption = "long" | "short" | "narrow";
/**
* A registry of named format parts. Each type of part has every option.
*/
interface NamedFormats {
weekday: Record<string, NamedFormatOption>;
month: Record<string, NamedFormatOption>;
dayPeriod: Record<string, NamedFormatOption>;
}
/**
* Internal format for "pieces" of a date form. Each part represents a single
* logical grouping, like "month", or "seconds".
*/
interface Part {
/**
* An object of partName to partValue For example:
* ```js
* { hour: '2-digit' }
* ```
*/
option: FormatPattern[1];
/**
* The name of the part, these must be valid parts of a date format as
* specified in Intl.DateTimeFormatPartTypes. Valid values are:
* day, dayPeriod, era, hour, literal, minute, month, second, timeZoneName,
* weekday, year
*/
partName: Intl.DateTimeFormatPartTypes;
/**
* The value of a given part. For example "2-digit", or "narrow".
*/
partValue: string;
/**
* The string token that represents the regex. For example "YYYY".
*/
token: string;
/**
* A regular expression if the above token.
*/
pattern: RegExp;
/**
* Does this part require a the hour12 clock.
*/
hour12: boolean;
}
/**
* A date part with an actual value applied.
*/
type FilledPart = Part & {
value: string;
};
/**
* A tuple describing a given formatting token.
*/
type FormatPattern = [
pattern: FormatToken | string,
option: Partial<Record<Intl.DateTimeFormatPartTypes, string>>,
exp?: RegExp
];
/**
* Possible options for a format style.
*/
type FormatStyle = "full" | "long" | "medium" | "short";
/**
* Possible objects for the dateStyle and timeStyle.
*/
type FormatStyleObj = {
date: FormatStyle;
time: FormatStyle;
} | {
date: FormatStyle;
} | {
time: FormatStyle;
};
type Format = FormatStyle | FormatStyleObj | string;
/**
* A union of all available formatting tokens.
*/
type FormatToken = "YYYY" | "YY" | "MMMM" | "MMM" | "MM" | "M" | "DD" | "D" | "dddd" | "ddd" | "d" | "mm" | "m" | "ss" | "s" | "HH" | "H" | "hh" | "h" | "a" | "A" | "ZZ" | "Z";
interface ParseOptions {
/**
* A string representing a date.
*/
date: string;
/**
* The format that should be used to parse the date. This is a string composed
* of tokens.
*/
format: Format;
/**
* The locale used to parse the date.
*/
locale: string;
/**
* A function that can be used to filter out parts of the format. This is
* useful when using the native Intl formats like
* `{ date: 'full', time: 'full' }` and not wanting to keep all the parts of
* the given format.
*/
partFilter?: (part: Part) => boolean;
/**
* The behavior to use when a date overflows a given month. For example, if
* the date to parse is February 29, 2023 — there is no 29th day of February.
* In this case overflow "forward" would result in March 1, 2023, "backward"
* would result in February 28, 2023, and "throw" would throw an error.
*/
dateOverflow?: "forward" | "backward" | "throw";
}
interface FormatOptions {
/**
* A date object or ISO 8601 string.
*/
date: DateInput;
/**
* A format string or object.
*/
format: Format;
/**
* A locale or en by default.
*/
locale?: string;
/**
* Whether or not to escape literals.
*/
genitive?: boolean;
/**
* A function to filter parts.
*/
tz?: string;
/**
* A function to filter parts.
*/
partFilter?: (part: Part) => boolean;
}
export type { DateInput, FilledPart, Format, FormatOptions, FormatPattern, FormatStyle, FormatStyleObj, FormatToken, NamedFormatOption, NamedFormats, ParseOptions, Part };
//# sourceMappingURL=types.mjs.map
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
import { DateInput } from './types.js';
/**
* Creates a date object for the input date at the given timezone. For example
* `tzDate("2017-05-06T12:00", "Europe/Amsterdam")` will return a date object
* for 2017-05-06T10:00:00Z since 12:00 in Amsterdam is 10:00Z.
*
* If given a Date object it will use local time and convert it to the given
* timezone, thus "changing" the date.
* @param inputDate - An iso8601 date string with no timezone
* @param tz - A timezone string
*/
declare function tzDate(inputDate: DateInput, tz: string): Date;
export { tzDate };
// src/tzDate.ts
import { offset } from "./offset.mjs";
import { applyOffset } from "./applyOffset.mjs";
import { date } from "./date.mjs";
function tzDate(inputDate, tz) {
const d = date(inputDate);
return applyOffset(d, offset(d, tz));
}
export {
tzDate
};
//# sourceMappingURL=tzDate.mjs.map
{"version":3,"sources":["../src/tzDate.ts"],"sourcesContent":["import { offset } from \"./offset\"\nimport { applyOffset } from \"./applyOffset\"\nimport { date } from \"./date\"\nimport { DateInput } from \"./types\"\n\n/**\n * Creates a date object for the input date at the given timezone. For example\n * `tzDate(\"2017-05-06T12:00\", \"Europe/Amsterdam\")` will return a date object\n * for 2017-05-06T10:00:00Z since 12:00 in Amsterdam is 10:00Z.\n *\n * If given a Date object it will use local time and convert it to the given\n * timezone, thus \"changing\" the date.\n * @param inputDate - An iso8601 date string with no timezone\n * @param tz - A timezone string\n */\nexport function tzDate(inputDate: DateInput, tz: string) {\n const d = date(inputDate)\n return applyOffset(d, offset(d, tz))\n}\n"],"mappings":";AAAA,SAAS,cAAc;AACvB,SAAS,mBAAmB;AAC5B,SAAS,YAAY;AAad,SAAS,OAAO,WAAsB,IAAY;AACvD,QAAM,IAAI,KAAK,SAAS;AACxB,SAAO,YAAY,GAAG,OAAO,GAAG,EAAE,CAAC;AACrC;","names":[]}
import { DateInput } from './types.js';
/**
* Returns a Date object for the last day at the last second of the given week.
* Defaults to Sunday as the first day of the week:
* 0 = Sunday ... 6 = Saturday
* @param inputDate - Gets the last day of the week
* @param startOfWeekDay - The first day of the week
*/
declare function weekEnd(inputDate: DateInput, startOfWeekDay?: number): Date;
export { weekEnd };
// src/weekEnd.ts
import { weekStart } from "./weekStart.mjs";
function weekEnd(inputDate, startOfWeekDay = 0) {
const d = weekStart(inputDate, startOfWeekDay);
d.setDate(d.getDate() + 6);
d.setHours(23, 59, 59);
return d;
}
export {
weekEnd
};
//# sourceMappingURL=weekEnd.mjs.map
{"version":3,"sources":["../src/weekEnd.ts"],"sourcesContent":["import { weekStart } from \"./weekStart\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Returns a Date object for the last day at the last second of the given week.\n * Defaults to Sunday as the first day of the week:\n * 0 = Sunday ... 6 = Saturday\n * @param inputDate - Gets the last day of the week\n * @param startOfWeekDay - The first day of the week\n */\nexport function weekEnd(inputDate: DateInput, startOfWeekDay = 0): Date {\n const d = weekStart(inputDate, startOfWeekDay)\n d.setDate(d.getDate() + 6)\n d.setHours(23, 59, 59)\n return d\n}\n"],"mappings":";AAAA,SAAS,iBAAiB;AAUnB,SAAS,QAAQ,WAAsB,iBAAiB,GAAS;AACtE,QAAM,IAAI,UAAU,WAAW,cAAc;AAC7C,IAAE,QAAQ,EAAE,QAAQ,IAAI,CAAC;AACzB,IAAE,SAAS,IAAI,IAAI,EAAE;AACrB,SAAO;AACT;","names":[]}
import { DateInput } from './types.js';
/**
* Returns a Date object for start of the given week. Defaults to Sunday as the
* first day of the week:
* 0 = Sunday ... 6 = Saturday
* @param inputDate - A string or Date object
* @param startOfWeekDay - Determines which day of the week is the first
*/
declare function weekStart(inputDate: DateInput, startOfWeekDay?: number): Date;
export { weekStart };
// src/weekStart.ts
import { date } from "./date.mjs";
function weekStart(inputDate, startOfWeekDay = 0) {
const d = date(inputDate);
let diff = startOfWeekDay - d.getDay();
if (diff > 0)
diff = diff - 7;
d.setDate(d.getDate() + diff);
d.setHours(0, 0, 0);
return d;
}
export {
weekStart
};
//# sourceMappingURL=weekStart.mjs.map
{"version":3,"sources":["../src/weekStart.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Returns a Date object for start of the given week. Defaults to Sunday as the\n * first day of the week:\n * 0 = Sunday ... 6 = Saturday\n * @param inputDate - A string or Date object\n * @param startOfWeekDay - Determines which day of the week is the first\n */\nexport function weekStart(inputDate: DateInput, startOfWeekDay = 0): Date {\n const d = date(inputDate)\n let diff = startOfWeekDay - d.getDay()\n if (diff > 0) diff = diff - 7\n d.setDate(d.getDate() + diff)\n d.setHours(0, 0, 0)\n return d\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAUd,SAAS,UAAU,WAAsB,iBAAiB,GAAS;AACxE,QAAM,IAAI,KAAK,SAAS;AACxB,MAAI,OAAO,iBAAiB,EAAE,OAAO;AACrC,MAAI,OAAO;AAAG,WAAO,OAAO;AAC5B,IAAE,QAAQ,EAAE,QAAQ,IAAI,IAAI;AAC5B,IAAE,SAAS,GAAG,GAAG,CAAC;AAClB,SAAO;AACT;","names":[]}
import { DateInput } from './types.js';
/**
* Get the number of days in the given date’s year.
* @param inputDate - A string or Date object
*/
declare function yearDays(inputDate: DateInput): number;
export { yearDays };
// src/yearDays.ts
import { date } from "./date.mjs";
function yearDays(inputDate) {
const d = date(inputDate);
return (new Date(d.getFullYear() + 1, 0, 0).getTime() - new Date(d.getFullYear(), 0, 0).getTime()) / 864e5;
}
export {
yearDays
};
//# sourceMappingURL=yearDays.mjs.map
{"version":3,"sources":["../src/yearDays.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Get the number of days in the given date’s year.\n * @param inputDate - A string or Date object\n */\nexport function yearDays(inputDate: DateInput): number {\n const d = date(inputDate)\n return (\n (new Date(d.getFullYear() + 1, 0, 0).getTime() -\n new Date(d.getFullYear(), 0, 0).getTime()) /\n 86400000\n )\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAOd,SAAS,SAAS,WAA8B;AACrD,QAAM,IAAI,KAAK,SAAS;AACxB,UACG,IAAI,KAAK,EAAE,YAAY,IAAI,GAAG,GAAG,CAAC,EAAE,QAAQ,IAC3C,IAAI,KAAK,EAAE,YAAY,GAAG,GAAG,CAAC,EAAE,QAAQ,KAC1C;AAEJ;","names":[]}
import { DateInput } from './types.js';
/**
* Returns a Date object for the with the input date set to the end of the current year.
* @param inputDate - A string or Date object
*/
declare function yearEnd(inputDate: DateInput): Date;
export { yearEnd };
// src/yearEnd.ts
import { date } from "./date.mjs";
function yearEnd(inputDate) {
const d = date(inputDate);
d.setMonth(11);
d.setDate(31);
d.setHours(23, 59, 59, 999);
return d;
}
export {
yearEnd
};
//# sourceMappingURL=yearEnd.mjs.map
{"version":3,"sources":["../src/yearEnd.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Returns a Date object for the with the input date set to the end of the current year.\n * @param inputDate - A string or Date object\n */\nexport function yearEnd(inputDate: DateInput): Date {\n const d = date(inputDate);\n\n d.setMonth(11);\n d.setDate(31);\n d.setHours(23, 59, 59, 999);\n\n return d;\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAOd,SAAS,QAAQ,WAA4B;AAClD,QAAM,IAAI,KAAK,SAAS;AAExB,IAAE,SAAS,EAAE;AACb,IAAE,QAAQ,EAAE;AACZ,IAAE,SAAS,IAAI,IAAI,IAAI,GAAG;AAE1B,SAAO;AACT;","names":[]}
import { DateInput } from './types.js';
/**
* Returns a Date object for the with the input date set to the start of the current year.
* @param inputDate - A string or Date object
*/
declare function yearStart(inputDate: DateInput): Date;
export { yearStart };
// src/yearStart.ts
import { date } from "./date.mjs";
function yearStart(inputDate) {
const d = date(inputDate);
d.setMonth(0);
d.setDate(1);
d.setHours(0, 0, 0);
return d;
}
export {
yearStart
};
//# sourceMappingURL=yearStart.mjs.map
{"version":3,"sources":["../src/yearStart.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { DateInput } from \"./types\"\n\n/**\n * Returns a Date object for the with the input date set to the start of the current year.\n * @param inputDate - A string or Date object\n */\nexport function yearStart(inputDate: DateInput): Date {\n const d = date(inputDate)\n\n d.setMonth(0)\n d.setDate(1)\n d.setHours(0, 0, 0)\n\n return d\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAOd,SAAS,UAAU,WAA4B;AACpD,QAAM,IAAI,KAAK,SAAS;AAExB,IAAE,SAAS,CAAC;AACZ,IAAE,QAAQ,CAAC;AACX,IAAE,SAAS,GAAG,GAAG,CAAC;AAElB,SAAO;AACT;","names":[]}
+139
-20

@@ -35,2 +35,10 @@ "use strict";

dayStart: () => dayStart,
diffDays: () => diffDays,
diffHours: () => diffHours,
diffMilliseconds: () => diffMilliseconds,
diffMinutes: () => diffMinutes,
diffMonths: () => diffMonths,
diffSeconds: () => diffSeconds,
diffWeeks: () => diffWeeks,
diffYears: () => diffYears,
format: () => format,

@@ -208,2 +216,3 @@ formatStr: () => formatStr,

["s", { second: "numeric" }],
["ZZ", { timeZoneName: "long" }],
["Z", { timeZoneName: "short" }]

@@ -279,3 +288,3 @@ ];

if (partName === "timeZoneName") {
return offset2 != null ? offset2 : minsToOffset(-1 * d.getTimezoneOffset());
return offset2 != null ? offset2 : minsToOffset(-1 * d.getTimezoneOffset(), token);
}

@@ -351,3 +360,3 @@ return value2;

}
function minsToOffset(timeDiffInMins) {
function minsToOffset(timeDiffInMins, token = "Z") {
const hours = String(Math.floor(Math.abs(timeDiffInMins / 60))).padStart(

@@ -359,12 +368,24 @@ 2,

const sign = timeDiffInMins < 0 ? "-" : "+";
return `${sign}${hours}${mins}`;
if (token === "ZZ") {
return `${sign}${hours}${mins}`;
}
return `${sign}${hours}:${mins}`;
}
function offsetToMins(offset2) {
validOffset(offset2);
const [_, sign, hours, mins] = offset2.match(/([+-])([0-3][0-9])([0-6][0-9])/);
function offsetToMins(offset2, token) {
validOffset(offset2, token);
const [_, sign, hours, mins] = offset2.match(
/([+-])([0-3][0-9]):?([0-6][0-9])/
);
const offsetInMins = Number(hours) * 60 + Number(mins);
return sign === "+" ? offsetInMins : -offsetInMins;
}
function validOffset(offset2) {
const valid = /^([+-])[0-3][0-9]:?[0-6][0-9]$/.test(offset2);
function validOffset(offset2, token = "Z") {
const valid = ((token2) => {
switch (token2) {
case "Z":
return /^([+-])[0-3][0-9]:[0-6][0-9]$/.test(offset2);
case "ZZ":
return /^([+-])[0-3][0-9][0-6][0-9]$/.test(offset2);
}
})(token);
if (!valid)

@@ -399,2 +420,8 @@ throw new Error(`Invalid offset: ${offset2}`);

}
function getOffsetFormat(format2) {
if (typeof format2 === "string") {
return format2.includes("ZZ") ? "ZZ" : "Z";
}
return "time" in format2 && format2.time === "full" ? "Z" : "ZZ";
}

@@ -426,5 +453,13 @@ // src/ap.ts

// src/applyOffset.ts
function applyOffset(dateInput, offset2 = "+0000") {
function applyOffset(dateInput, offset2 = "+00:00") {
const d = date(dateInput);
const timeDiffInMins = offsetToMins(offset2);
const token = (() => {
switch (fixedLengthByOffset(offset2)) {
case 5:
return "ZZ";
case 6:
return "Z";
}
})();
const timeDiffInMins = offsetToMins(offset2, token);
return new Date(d.getTime() + timeDiffInMins * 1e3 * 60);

@@ -458,3 +493,3 @@ }

}
function offset(utcTime, tzA = "UTC", tzB = "device") {
function offset(utcTime, tzA = "UTC", tzB = "device", timeZoneToken = "Z") {
var _a;

@@ -466,3 +501,3 @@ tzB = tzB === "device" ? (_a = deviceTZ()) != null ? _a : "utc" : tzB;

const timeDiffInMins = (timeB.getTime() - timeA.getTime()) / 1e3 / 60;
return minsToOffset(timeDiffInMins);
return minsToOffset(timeDiffInMins, timeZoneToken);
}

@@ -584,3 +619,4 @@

locale,
part.type === "hour" ? hourType : void 0
part.type === "hour" ? hourType : void 0,
options
);

@@ -604,3 +640,3 @@ if (formatPattern === void 0)

}
function guessPattern(partName, partValue, locale, hour) {
function guessPattern(partName, partValue, locale, hour, options) {
const l = partValue.length;

@@ -647,4 +683,3 @@ const n = !isNaN(Number(partValue));

case "timeZoneName":
const offset2 = partValue.split("-");
return offset2.length === 2 && offset2[1].length === 4 ? tokens.get("ZZ") : tokens.get("Z");
return options.timeStyle === "full" ? tokens.get("Z") : tokens.get("ZZ");
default:

@@ -703,3 +738,3 @@ return void 0;

// src/removeOffset.ts
function removeOffset(dateInput, offset2 = "+0000") {
function removeOffset(dateInput, offset2 = "+00:00") {
const positive = offset2.slice(0, 1) === "+";

@@ -734,3 +769,3 @@ return applyOffset(

if (tz) {
forceOffset = offset(inputDateOrOptions, "utc", tz);
forceOffset = offset(inputDateOrOptions, "utc", tz, getOffsetFormat(format2));
}

@@ -967,4 +1002,4 @@ tz != null ? tz : tz = deviceTZ();

a = part.value.toLowerCase() === ap("am", locale).toLowerCase();
} else if (t === "Z") {
offset2 = validOffset(part.value);
} else if (t === "Z" || t === "ZZ") {
offset2 = validOffset(part.value, t);
} else {

@@ -1142,2 +1177,78 @@ const values = range(t, locale, genitive);

}
// src/diffMilliseconds.ts
function diffMilliseconds(dateA, dateB) {
const left = date(dateA);
const right = date(dateB);
return +left - +right;
}
// src/diffRound.ts
function diffRound(value, method = "trunc") {
const r = Math[method](value);
return r == 0 ? 0 : r;
}
// src/diffSeconds.ts
function diffSeconds(dateA, dateB, roundingMethod) {
return diffRound(diffMilliseconds(dateA, dateB) / 1e3, roundingMethod);
}
// src/diffMinutes.ts
function diffMinutes(dateA, dateB, roundingMethod) {
return diffRound(diffMilliseconds(dateA, dateB) / 6e4, roundingMethod);
}
// src/diffHours.ts
function diffHours(dateA, dateB, roundingMethod) {
return diffRound(
diffMilliseconds(dateA, dateB) / 36e5,
// 1000 * 60 * 60
roundingMethod
);
}
// src/diffDays.ts
function diffDays(dateA, dateB, roundingMethod) {
return diffRound(
diffMilliseconds(dateA, dateB) / 864e5,
// hour * 24
roundingMethod
);
}
// src/diffWeeks.ts
function diffWeeks(dateA, dateB, roundingMethod) {
return diffRound(
diffMilliseconds(dateA, dateB) / 6048e5,
// day * 7
roundingMethod
);
}
// src/diffMonths.ts
function diffMonths(dateA, dateB) {
const l = date(dateA);
const r = date(dateB);
if (l < r) {
const rs = diffMonths(r, l);
return rs == 0 ? 0 : -rs;
}
let months = (l.getFullYear() - r.getFullYear()) * 12 + (l.getMonth() - r.getMonth());
const ld = l.getDate();
const rd = r.getDate();
if (ld < rd) {
const lm = monthDays(l);
if (!(lm == ld && lm < rd)) {
months--;
}
}
return months == 0 ? 0 : months;
}
// src/diffYears.ts
function diffYears(dateA, dateB) {
const r = Math.trunc(diffMonths(dateA, dateB) / 12);
return r == 0 ? 0 : r;
}
// Annotate the CommonJS export names for ESM import in node:

@@ -1157,2 +1268,10 @@ 0 && (module.exports = {

dayStart,
diffDays,
diffHours,
diffMilliseconds,
diffMinutes,
diffMonths,
diffSeconds,
diffWeeks,
diffYears,
format,

@@ -1159,0 +1278,0 @@ formatStr,

@@ -198,3 +198,3 @@ /**

* @param dateInput - The date to apply the offset to.
* @param offset - The offset to apply in the +-HHmm format.
* @param offset - The offset to apply in the +-HHmm or +-HH:mm format.
*/

@@ -351,2 +351,11 @@ declare function applyOffset(dateInput: DateInput, offset?: string): Date;

/**
* Timezone tokens.
*/
declare const timeZoneTokens: readonly ["Z", "ZZ"];
/**
* Timezone token type.
*/
type TimezoneToken = (typeof timeZoneTokens)[number];
/**
* Returns the offset between two timezones on a given date. The results are

@@ -359,3 +368,3 @@ * ISO8601 compatible offsets like -0800 or +0530.

*/
declare function offset(utcTime: DateInput, tzA?: string, tzB?: string): string;
declare function offset(utcTime: DateInput, tzA?: string, tzB?: string, timeZoneToken?: TimezoneToken): string;

@@ -391,3 +400,3 @@ declare function parse(options: ParseOptions): Date | never;

* @param dateInput - The date to remove the offset from.
* @param offset - The offset to remove in the +-HHmm format.
* @param offset - The offset to remove in the +-HHmm or +-HH:mm format.
*/

@@ -502,2 +511,64 @@ declare function removeOffset(dateInput: DateInput, offset?: string): Date;

export { type DateInput, type FilledPart, type Format, type FormatOptions, type FormatPattern, type FormatStyle, type FormatStyleObj, type FormatToken, type NamedFormatOption, type NamedFormats, type ParseOptions, type Part, addDay, addHour, addMinute, addMonth, addSecond, addYear, ap, applyOffset, date, dayEnd, dayOfYear, dayStart, format, formatStr, fourDigitYear, hourEnd, hourStart, isAfter, isBefore, isEqual, iso8601, minuteEnd, minuteStart, monthDays, monthEnd, monthStart, nearestDay, offset, parse, parseParts, parts, range, removeOffset, sameDay, sameHour, sameMinute, sameSecond, sameYear, tzDate, weekEnd, weekStart, yearDays, yearEnd, yearStart };
/**
* Returns the difference between 2 dates in milliseconds.
* @param dateA A date to compare with the right date
* @param dateB A date to compare with the left date
*/
declare function diffMilliseconds(dateA: DateInput, dateB: DateInput): number;
type DiffRoundingMethod = "trunc" | "round" | "floor" | "ceil";
/**
* Returns the difference between 2 dates in seconds.
* @param dateA A date to compare with the right date
* @param dateB A date to compare with the left date
* @param roundingMethod the rounding method to use, default: trunc
*/
declare function diffSeconds(dateA: DateInput, dateB: DateInput, roundingMethod?: DiffRoundingMethod): number;
/**
* Returns the difference between 2 dates in minutes.
* @param dateA A date to compare with the right date
* @param roundingMethod the rounding method to use, default: trunc
*/
declare function diffMinutes(dateA: DateInput, dateB: DateInput, roundingMethod?: DiffRoundingMethod): number;
/**
* Returns the difference between 2 dates in hours.
* @param dateA A date to compare with the right date
* @param dateB A date to compare with the left date
* @param roundingMethod the rounding method to use, default: trunc
*/
declare function diffHours(dateA: DateInput, dateB: DateInput, roundingMethod?: DiffRoundingMethod): number;
/**
* Returns the difference between 2 dates in days.
* @param dateA A date to compare with the right date
* @param dateB A date to compare with the left date
* @param roundingMethod the rounding method to use, default: trunc
*/
declare function diffDays(dateA: DateInput, dateB: DateInput, roundingMethod?: DiffRoundingMethod): number;
/**
* Returns the difference between 2 dates in days.
* @param dateA A date to compare with the right date
* @param dateB A date to compare with the left date
* @param roundingMethod the rounding method to use, default: trunc
*/
declare function diffWeeks(dateA: DateInput, dateB: DateInput, roundingMethod?: DiffRoundingMethod): number;
/**
* Returns the difference between 2 dates in months.
* @param dateA A date to compare with the dateB date
* @param dateB A date to compare with the dateA date
*/
declare function diffMonths(dateA: DateInput, dateB: DateInput): number;
/**
* Returns the difference between 2 dates in years.
* @param dateA A date to compare with the dateB date
* @param dateB A date to compare with the dateA date
*/
declare function diffYears(dateA: DateInput, dateB: DateInput): number;
export { type DateInput, type FilledPart, type Format, type FormatOptions, type FormatPattern, type FormatStyle, type FormatStyleObj, type FormatToken, type NamedFormatOption, type NamedFormats, type ParseOptions, type Part, addDay, addHour, addMinute, addMonth, addSecond, addYear, ap, applyOffset, date, dayEnd, dayOfYear, dayStart, diffDays, diffHours, diffMilliseconds, diffMinutes, diffMonths, diffSeconds, diffWeeks, diffYears, format, formatStr, fourDigitYear, hourEnd, hourStart, isAfter, isBefore, isEqual, iso8601, minuteEnd, minuteStart, monthDays, monthEnd, monthStart, nearestDay, offset, parse, parseParts, parts, range, removeOffset, sameDay, sameHour, sameMinute, sameSecond, sameYear, tzDate, weekEnd, weekStart, yearDays, yearEnd, yearStart };
+54
-498

@@ -1,498 +0,54 @@

/**
* The date format used as an input value. Either a date or an ISO8601 string.
*/
type DateInput = Date | string;
/**
* Format parts with text names use these descriptors:
*/
type NamedFormatOption = "long" | "short" | "narrow";
/**
* A registry of named format parts. Each type of part has every option.
*/
interface NamedFormats {
weekday: Record<string, NamedFormatOption>;
month: Record<string, NamedFormatOption>;
dayPeriod: Record<string, NamedFormatOption>;
}
/**
* Internal format for "pieces" of a date form. Each part represents a single
* logical grouping, like "month", or "seconds".
*/
interface Part {
/**
* An object of partName to partValue For example:
* ```js
* { hour: '2-digit' }
* ```
*/
option: FormatPattern[1];
/**
* The name of the part, these must be valid parts of a date format as
* specified in Intl.DateTimeFormatPartTypes. Valid values are:
* day, dayPeriod, era, hour, literal, minute, month, second, timeZoneName,
* weekday, year
*/
partName: Intl.DateTimeFormatPartTypes;
/**
* The value of a given part. For example "2-digit", or "narrow".
*/
partValue: string;
/**
* The string token that represents the regex. For example "YYYY".
*/
token: string;
/**
* A regular expression if the above token.
*/
pattern: RegExp;
/**
* Does this part require a the hour12 clock.
*/
hour12: boolean;
}
/**
* A date part with an actual value applied.
*/
type FilledPart = Part & {
value: string;
};
/**
* A tuple describing a given formatting token.
*/
type FormatPattern = [
pattern: FormatToken | string,
option: Partial<Record<Intl.DateTimeFormatPartTypes, string>>,
exp?: RegExp
];
/**
* Possible options for a format style.
*/
type FormatStyle = "full" | "long" | "medium" | "short";
/**
* Possible objects for the dateStyle and timeStyle.
*/
type FormatStyleObj = {
date: FormatStyle;
time: FormatStyle;
} | {
date: FormatStyle;
} | {
time: FormatStyle;
};
type Format = FormatStyle | FormatStyleObj | string;
/**
* A union of all available formatting tokens.
*/
type FormatToken = "YYYY" | "YY" | "MMMM" | "MMM" | "MM" | "M" | "DD" | "D" | "dddd" | "ddd" | "d" | "mm" | "m" | "ss" | "s" | "HH" | "H" | "hh" | "h" | "a" | "A" | "ZZ" | "Z";
interface ParseOptions {
/**
* A string representing a date.
*/
date: string;
/**
* The format that should be used to parse the date. This is a string composed
* of tokens.
*/
format: Format;
/**
* The locale used to parse the date.
*/
locale: string;
/**
* A function that can be used to filter out parts of the format. This is
* useful when using the native Intl formats like
* `{ date: 'full', time: 'full' }` and not wanting to keep all the parts of
* the given format.
*/
partFilter?: (part: Part) => boolean;
/**
* The behavior to use when a date overflows a given month. For example, if
* the date to parse is February 29, 2023 — there is no 29th day of February.
* In this case overflow "forward" would result in March 1, 2023, "backward"
* would result in February 28, 2023, and "throw" would throw an error.
*/
dateOverflow?: "forward" | "backward" | "throw";
}
interface FormatOptions {
/**
* A date object or ISO 8601 string.
*/
date: DateInput;
/**
* A format string or object.
*/
format: Format;
/**
* A locale or en by default.
*/
locale?: string;
/**
* Whether or not to escape literals.
*/
genitive?: boolean;
/**
* A function to filter parts.
*/
tz?: string;
/**
* A function to filter parts.
*/
partFilter?: (part: Part) => boolean;
}
/**
* Returns a new date object 1/n days after the original one.
* @param inputDate - A date to increment by 1 day.
*/
declare function addDay(inputDate: DateInput, count?: number): Date;
/**
* Returns a new date object 1/n months after the original one. Keep in mind if you
* start with a date late in a given month you could get a date after the next
* month.
* @param inputDate - A date to increment by 1 or more months.
* @param count - The quantity to add.
* @param dateOverflow - Whether or not to allow the date to overflow to another month if the inputDate’s month is out of range of the new month.
*/
declare function addMonth(inputDate: DateInput, count?: number, dateOverflow?: boolean): Date;
/**
* Returns a new date object 1/n years after the original one. Keep in mind if
* you start with a date late in a given month you could get a date after the
* next month.
* @param inputDate - A date to increment by 1 day.
* @param count - The quantity of years add.
* @param dateOverflow - Whether or not to allow the date to overflow to another month if the inputDate’s month is out of range of the new month.
*/
declare function addYear(inputDate: DateInput, count?: number, dateOverflow?: boolean): Date;
/**
* Returns a new date object 1/n hours after the original one.
* @param inputDate - A date to increment by 1 day.
*/
declare function addHour(inputDate: DateInput, count?: number): Date;
/**
* Returns a new date object 1/n seconds after the original one.
* @param inputDate - A date to increment by 1 day.
*/
declare function addMinute(inputDate: DateInput, count?: number): Date;
/**
* Returns a new date object 1/n seconds after the original one.
* @param inputDate - A date to increment by 1 day.
*/
declare function addSecond(inputDate: DateInput, count?: number): Date;
/**
* Determines the correct value for am/pm by locale and memoizes it.
* @param ampm - am or pm
* @param locale - The locale to fetch.
*/
declare function ap(ampm: "am" | "pm", locale: string): string;
/**
* Apply a given offset to a date, returning a new date with the offset
* applied by adding or subtracting the given number of minutes.
* @param dateInput - The date to apply the offset to.
* @param offset - The offset to apply in the +-HHmm format.
*/
declare function applyOffset(dateInput: DateInput, offset?: string): Date;
/**
* A date to parse.
* @param date - A Date object or an ISO 8601 date.
*/
declare function date(date?: DateInput): Date;
/**
* Creates a date object for the input date at the given timezone. For example
* `tzDate("2017-05-06T12:00", "Europe/Amsterdam")` will return a date object
* for 2017-05-06T10:00:00Z since 12:00 in Amsterdam is 10:00Z.
*
* If given a Date object it will use local time and convert it to the given
* timezone, thus "changing" the date.
* @param inputDate - An iso8601 date string with no timezone
* @param tz - A timezone string
*/
declare function tzDate(inputDate: DateInput, tz: string): Date;
/**
* Gets the what day of the year a given date is. For example, August 1st is
* the 213th day of the year on non- years and 214th on leap years.
* @param inputDate - The input date.
*/
declare function dayOfYear(inputDate: DateInput): number;
/**
* Returns a Date object for end of the given day.
* @param inputDate - A string or Date object
*/
declare function dayEnd(inputDate: DateInput): Date;
/**
* Returns a Date object for start of the given day.
* @param inputDate - A string or Date object
*/
declare function dayStart(inputDate: DateInput): Date;
/**
* Produce a formatted string. Available strings:
* token | description
* ------|------------
* YY | 2 digit year
* YYYY | 4 digit year
* M | The month 1-12
* MM | The month 01-12
* MMM | Short name Jan-Dec
* MMMM | Full name January | December
* D | The day of the month 1-31
* DD | The day of the month 01-31
* d | Single digit day "T"
* ddd | Short day name Thu
* dddd | Full day name Wednesday
* H | Minimum hour digits, 24 hour, 0-23
* HH | 2 hour digits, 24 hour, 00-23
* h | Minimum hour digits, 12 hour clock, 1-12
* hh | 2 hour digits, 12 hour clock, 01-12
* m | The minute 0-59
* mm | The minute 00-59
* s | The second 0-59
* ss | The second 00-59
* a | am/pm
* A | AM/PM
* Z | +0800, +0530, -1345
*
* @param inputDate - A date object or ISO 8601 string
* @param format - A format
*/
declare function format(options: FormatOptions): string;
declare function format(inputDate: DateInput, format?: Format, locale?: string, genitive?: boolean, partFilter?: (part: Part) => boolean): string;
/**
* Return the string format for a given format. For example:
* ```js
* formatStr({ date: 'long' }, 'en') // dddd, MMMM D, YYYY
* ```
* @param format - A format string or object.
* @param locale - A locale or en by default.
*/
declare function formatStr(format: Format, locale?: string, escapeLiterals?: boolean, filterParts?: (part: Part) => boolean): string;
/**
* Converts a 2 digit year into a 4 digit year. This function assumes years 20
* years into the future belong to the current century, and the past 80 are in
* the past.
*
* @param value - 2 digits in string format
*/
declare function fourDigitYear(value: string): number;
/**
* Returns a Date object for end of the given hour.
* @param inputDate - A string or Date object
*/
declare function hourEnd(inputDate: DateInput): Date;
/**
* Returns a Date object for start of the given hour.
* @param inputDate - A string or Date object
*/
declare function hourStart(inputDate: DateInput): Date;
/**
* True when the date string is valid ISO 8601.
* @param date - A date string.
*/
declare function iso8601(date: string): boolean;
/**
* Returns a Date object for end of the given minute.
* @param inputDate - A string or Date object
*/
declare function minuteEnd(inputDate: DateInput): Date;
/**
* Returns a Date object for start of the given minute.
* @param inputDate - A string or Date object
*/
declare function minuteStart(inputDate: DateInput): Date;
/**
* Returns the total number of days from a given month.
* @param inputDate - A string or Date object
*/
declare function monthDays(inputDate: DateInput): number;
/**
* Returns a Date object for the with the input date set to the last day of
* the current month. Does not change the time.
* @param inputDate - A string or Date object
*/
declare function monthEnd(inputDate: DateInput): Date;
/**
* Returns a Date object for the first day of a month.
* @param inputDate - A string or Date object
*/
declare function monthStart(inputDate: DateInput): Date;
/**
* Performs a bidirectional search for the nearest date that passes a function.
* @param target - Performs a search for the nearest passing date.
* @param search - The search function to use, given a date returns a boolean.
* @param constraint - The number of iterations to perform before giving up, or logical constraint like "month", or "week".
*
*/
declare function nearestDay(inputDate: DateInput, search: (date: Date) => boolean, constraint?: number | "month" | "week" | "year"): Date | null;
/**
* Returns the offset between two timezones on a given date. The results are
* ISO8601 compatible offsets like -0800 or +0530.
*
* @param dateInput - The date on which to determine the offset.
* @param tzA - (default: UTC) The second timezone to compare determine the offset between.
* @param tzB - (default: device) The first timezone to compare determine the offset between.
*/
declare function offset(utcTime: DateInput, tzA?: string, tzB?: string): string;
declare function parse(options: ParseOptions): Date | never;
declare function parse(dateStr: string, format?: Format, locale?: string): Date | never;
/**
* Given a string date and corresponding format parts, fill the parts with the
* data from the string.
* @param dateStr - A string to parse.
* @param formatParts - The expected parts of the given string.
*/
declare function parseParts(dateStr: string, formatParts: Part[]): FilledPart[];
/**
* Given a format string, produce an array of matching "parts", each part
* contains a regular expression and the corresponding
* Intl.DateTimeFormatPartTypesRegistry key/value.
* @param format - A format string like MM/DD/YYYY
* @param locale - The locale to parse for.
*/
declare function parts(format: Format, locale: string): Part[];
/**
* Returns an array of options for a given token in a given locale.
* @param token - Get the full range of options for a given token
* @param locale - The locale to fetch the options for.
*/
declare function range(token: FormatToken, locale?: string, genitive?: boolean): string[];
/**
* Inverts the offset and applies it to the given date, returning a new date.
* @param dateInput - The date to remove the offset from.
* @param offset - The offset to remove in the +-HHmm format.
*/
declare function removeOffset(dateInput: DateInput, offset?: string): Date;
/**
* Checks if two date objects refer to the same date. Ignores time.
* @param inputDateA - First date to compare
* @param inputDateB - Second date to compare
*/
declare function sameDay(inputDateA: DateInput, inputDateB: DateInput): boolean;
/**
* Checks if two date objects refer to the same time seconds. Ignores date.
* @param inputDateA - First date to compare
* @param inputDateB - Second date to compare
*/
declare function sameSecond(inputDateA: DateInput, inputDateB: DateInput): boolean;
/**
* Checks if two date objects refer to the same time minutes. Ignores date.
* @param inputDateA - First date to compare
* @param inputDateB - Second date to compare
*/
declare function sameMinute(inputDateA: DateInput, inputDateB: DateInput): boolean;
/**
* Checks if two date objects refer to the same time hour. Ignores date.
* @param inputDateA - First date to compare
* @param inputDateB - Second date to compare
*/
declare function sameHour(inputDateA: DateInput, inputDateB: DateInput): boolean;
/**
* Checks if two date objects refer to the same year.
* @param inputDateA - First date to compare
* @param inputDateB - Second date to compare
*/
declare function sameYear(inputDateA: DateInput, inputDateB: DateInput): boolean;
/**
* Returns a Date object for the last day at the last second of the given week.
* Defaults to Sunday as the first day of the week:
* 0 = Sunday ... 6 = Saturday
* @param inputDate - Gets the last day of the week
* @param startOfWeekDay - The first day of the week
*/
declare function weekEnd(inputDate: DateInput, startOfWeekDay?: number): Date;
/**
* Returns a Date object for start of the given week. Defaults to Sunday as the
* first day of the week:
* 0 = Sunday ... 6 = Saturday
* @param inputDate - A string or Date object
* @param startOfWeekDay - Determines which day of the week is the first
*/
declare function weekStart(inputDate: DateInput, startOfWeekDay?: number): Date;
/**
* Get the number of days in the given date’s year.
* @param inputDate - A string or Date object
*/
declare function yearDays(inputDate: DateInput): number;
/**
* Returns a Date object for the with the input date set to the start of the current year.
* @param inputDate - A string or Date object
*/
declare function yearStart(inputDate: DateInput): Date;
/**
* Returns a Date object for the with the input date set to the end of the current year.
* @param inputDate - A string or Date object
*/
declare function yearEnd(inputDate: DateInput): Date;
/**
* Is the first date before the second one?
*
* @param inputDate - The date that should be before the other one to return true
* @param dateToCompare - The date to compare with
*
* @returns The first date is before the second date.
*/
declare function isBefore(inputDate: DateInput, dateToCompare: DateInput): boolean;
/**
* @name isAfter
* @category Common Helpers
* @summary Is the first date after the second one?
*
* @description
* Is the first date after the second one?
*
* @param inputDate - The date that should be after the other one to return true
* @param dateToCompare - The date to compare with
*
* @returns The first date is after the second date.
*/
declare function isAfter(inputDate: DateInput, dateToCompare: DateInput): boolean;
/**
* Are the given dates equal?
*
* @param dateLeft - The first date to compare
* @param dateRight - The second date to compare
*
* @returns The dates are equal.
*/
declare function isEqual(dateLeft: DateInput, dateRight: DateInput): boolean;
export { type DateInput, type FilledPart, type Format, type FormatOptions, type FormatPattern, type FormatStyle, type FormatStyleObj, type FormatToken, type NamedFormatOption, type NamedFormats, type ParseOptions, type Part, addDay, addHour, addMinute, addMonth, addSecond, addYear, ap, applyOffset, date, dayEnd, dayOfYear, dayStart, format, formatStr, fourDigitYear, hourEnd, hourStart, isAfter, isBefore, isEqual, iso8601, minuteEnd, minuteStart, monthDays, monthEnd, monthStart, nearestDay, offset, parse, parseParts, parts, range, removeOffset, sameDay, sameHour, sameMinute, sameSecond, sameYear, tzDate, weekEnd, weekStart, yearDays, yearEnd, yearStart };
export { addDay } from './addDay.js';
export { addMonth } from './addMonth.js';
export { addYear } from './addYear.js';
export { addHour } from './addHour.js';
export { addMinute } from './addMinute.js';
export { addSecond } from './addSecond.js';
export { ap } from './ap.js';
export { applyOffset } from './applyOffset.js';
export { date } from './date.js';
export { tzDate } from './tzDate.js';
export { dayOfYear } from './dayOfYear.js';
export { dayEnd } from './dayEnd.js';
export { dayStart } from './dayStart.js';
export { format } from './format.js';
export { formatStr } from './formatStr.js';
export { fourDigitYear } from './fourDigitYear.js';
export { hourEnd } from './hourEnd.js';
export { hourStart } from './hourStart.js';
export { iso8601 } from './iso8601.js';
export { minuteEnd } from './minuteEnd.js';
export { minuteStart } from './minuteStart.js';
export { monthDays } from './monthDays.js';
export { monthEnd } from './monthEnd.js';
export { monthStart } from './monthStart.js';
export { nearestDay } from './nearestDay.js';
export { offset } from './offset.js';
export { parse, parseParts } from './parse.js';
export { parts } from './parts.js';
export { range } from './range.js';
export { removeOffset } from './removeOffset.js';
export { sameDay } from './sameDay.js';
export { sameSecond } from './sameSecond.js';
export { sameMinute } from './sameMinute.js';
export { sameHour } from './sameHour.js';
export { sameYear } from './sameYear.js';
export { weekEnd } from './weekEnd.js';
export { weekStart } from './weekStart.js';
export { yearDays } from './yearDays.js';
export { yearStart } from './yearStart.js';
export { yearEnd } from './yearEnd.js';
export { isBefore } from './isBefore.js';
export { isAfter } from './isAfter.js';
export { isEqual } from './isEqual.js';
export { DateInput, FilledPart, Format, FormatOptions, FormatPattern, FormatStyle, FormatStyleObj, FormatToken, NamedFormatOption, NamedFormats, ParseOptions, Part } from './types.js';
export { diffMilliseconds } from './diffMilliseconds.js';
export { diffSeconds } from './diffSeconds.js';
export { diffMinutes } from './diffMinutes.js';
export { diffHours } from './diffHours.js';
export { diffDays } from './diffDays.js';
export { diffWeeks } from './diffWeeks.js';
export { diffMonths } from './diffMonths.js';
export { diffYears } from './diffYears.js';
import './common.js';
import './diffRound.js';

@@ -1,1058 +0,55 @@

// src/iso8601.ts
var iso8601Match = /^([0-9]{4})-([0-1][0-9])(?:-([0-3][0-9]))?(?:[T ]?([0-2][0-9])(?::([0-5][0-9]))?(?::([0-5][0-9]))?)?(?:\.[0-9]+)?(Z|(?:\+|\-)[0-9]{2}:?[0-9]{2})?$/;
function iso8601(date2) {
const matches = date2.match(iso8601Match);
if (matches) {
const month = Number(matches[2]);
if (month < 1 || month > 12)
return false;
if (typeof matches[3] !== void 0) {
const date3 = Number(matches[3]);
if (date3 < 1 || date3 > 31)
return false;
}
if (typeof matches[4] !== void 0) {
const hours = Number(matches[4]);
if (hours < 0 || hours > 23)
return false;
}
return true;
}
return false;
}
// src/date.ts
function normalize(date2) {
const matches = date2.match(iso8601Match);
if (matches && typeof matches[4] === "undefined") {
return date2 += "T00:00:00";
}
return date2;
}
function date(date2) {
if (!date2) {
date2 = /* @__PURE__ */ new Date();
}
if (date2 instanceof Date) {
const d = new Date(date2);
d.setMilliseconds(0);
return d;
}
date2 = date2.trim();
if (iso8601(date2)) {
return new Date(normalize(date2));
}
throw new Error(`Non ISO 8601 compliant date (${date2}).`);
}
// src/addDay.ts
function addDay(inputDate, count = 1) {
const d = date(inputDate);
d.setDate(d.getDate() + count);
return d;
}
// src/monthEnd.ts
function monthEnd(inputDate) {
const d = date(inputDate);
d.setDate(1);
d.setMonth(d.getMonth() + 1);
d.setDate(0);
return d;
}
// src/monthDays.ts
function monthDays(inputDate) {
const d = monthEnd(inputDate);
return d.getDate();
}
// src/addMonth.ts
function addMonth(inputDate, count = 1, dateOverflow = false) {
const d = date(inputDate);
const dayOfMonth = d.getDate();
if (!dateOverflow)
d.setDate(1);
d.setMonth(d.getMonth() + count);
if (!dateOverflow) {
const daysInMonth = monthDays(d);
d.setDate(daysInMonth < dayOfMonth ? daysInMonth : dayOfMonth);
}
return d;
}
// src/addYear.ts
function addYear(inputDate, count = 1, dateOverflow = false) {
const d = date(inputDate);
const dayOfMonth = d.getDate();
if (!dateOverflow)
d.setDate(1);
d.setFullYear(d.getFullYear() + count);
if (!dateOverflow) {
const daysInMonth = monthDays(d);
d.setDate(daysInMonth < dayOfMonth ? daysInMonth : dayOfMonth);
}
return d;
}
// src/addHour.ts
function addHour(inputDate, count = 1) {
const d = date(inputDate);
d.setHours(d.getHours() + count);
return d;
}
// src/addMinute.ts
function addMinute(inputDate, count = 1) {
const d = date(inputDate);
d.setMinutes(d.getMinutes() + count);
return d;
}
// src/addSecond.ts
function addSecond(inputDate, count = 1) {
const d = date(inputDate);
d.setSeconds(d.getSeconds() + count);
return d;
}
// src/common.ts
var specDate = "1999-03-04T02:05:01.000Z";
var memoParts = /* @__PURE__ */ new Map();
var clockAgnostic = [
["YYYY", { year: "numeric" }],
["YY", { year: "2-digit" }],
["MMMM", { month: "long" }],
["MMM", { month: "short" }],
["MM", { month: "2-digit" }],
["M", { month: "numeric" }],
["DD", { day: "2-digit" }],
["D", { day: "numeric" }],
["dddd", { weekday: "long" }],
["ddd", { weekday: "short" }],
["d", { weekday: "narrow" }],
["mm", { minute: "2-digit" }],
["m", { minute: "numeric" }],
["ss", { second: "2-digit" }],
["s", { second: "numeric" }],
["Z", { timeZoneName: "short" }]
];
var clock24 = [
["HH", { hour: "2-digit" }],
["H", { hour: "numeric" }]
];
var clock12 = [
["hh", { hour: "2-digit" }],
["h", { hour: "numeric" }],
["a", { dayPeriod: "narrow" }],
["A", { dayPeriod: "narrow" }]
];
var fixedLength = {
DD: 2,
HH: 2,
MM: 2,
YY: 2,
YYYY: 4,
hh: 2,
mm: 2,
ss: 2
};
function fixedLengthByOffset(offsetString) {
if (/^[+-]\d{2}:\d{2}/.test(offsetString)) {
return 6;
}
if (/^[+-]\d{4}/.test(offsetString)) {
return 5;
}
throw new Error("Invalid offset format");
}
var genitiveTokens = ["MMMM", "MMM", "dddd", "ddd"];
var tokens = /* @__PURE__ */ new Map(
/* @__PURE__ */ [...clockAgnostic, ...clock24, ...clock12].map((format2) => {
return [format2[0], format2];
})
);
var dayPeriodMap = /* @__PURE__ */ new Map();
var styles = [
"full",
"long",
"medium",
"short"
];
var two = (n) => String(n).padStart(2, "0");
var four = (n) => String(n).padStart(2, "0");
function normStr(part) {
if (part.type === "literal") {
part.value = part.value.normalize("NFKC");
}
return part;
}
function fill(inputDate, parts2, locale, genitive = false, offset2 = null) {
const partMap = createPartMap(inputDate, parts2, locale, genitive);
const d = date(inputDate);
function value({ partName, partValue, token }) {
if (partName === "literal")
return partValue;
const value2 = partMap[partName];
if (partName === "hour" && token === "H") {
return value2.replace(/^0/, "") || "0";
}
if (["mm", "ss", "MM"].includes(token) && value2.length === 1) {
return `0${value2}`;
}
if (partName === "dayPeriod") {
const p = ap(d.getUTCHours() < 12 ? "am" : "pm", locale);
return token === "A" ? p.toUpperCase() : p.toLowerCase();
}
if (partName === "timeZoneName") {
return offset2 != null ? offset2 : minsToOffset(-1 * d.getTimezoneOffset());
}
return value2;
}
return parts2.map((part) => {
return {
...part,
value: value(part)
};
});
}
function createPartMap(inputDate, parts2, locale, genitive = false) {
const d = date(inputDate);
const hour12 = parts2.filter((part) => part.hour12);
const hour24 = parts2.filter((part) => !part.hour12);
const valueParts = [];
const genitiveParts = [];
function addValues(requestedParts, hour122 = false) {
const preciseLocale = `${locale}-u-hc-${hour122 ? "h12" : "h23"}`;
valueParts.push(
...new Intl.DateTimeFormat(
preciseLocale,
requestedParts.reduce(
(options, part) => {
if (part.partName === "literal")
return options;
if (genitive && genitiveTokens.includes(part.token)) {
genitiveParts.push(part);
}
return Object.assign(options, part.option);
},
{ timeZone: "UTC" }
)
).formatToParts(d).map(normStr)
);
if (genitive && genitiveParts.length) {
for (const part of genitiveParts) {
let formattedParts = [];
switch (part.token) {
case "MMMM":
formattedParts = new Intl.DateTimeFormat(preciseLocale, {
dateStyle: "long",
timeZone: "UTC"
}).formatToParts(d).map(normStr);
break;
case "MMM":
formattedParts = new Intl.DateTimeFormat(preciseLocale, {
dateStyle: "medium",
timeZone: "UTC"
}).formatToParts(d).map(normStr);
break;
}
const genitiveFormattedPart = formattedParts.find(
(p) => p.type === part.partName
);
const index = valueParts.findIndex((p) => p.type === part.partName);
if (genitiveFormattedPart && index > -1) {
valueParts[index] = genitiveFormattedPart;
}
}
}
}
if (hour12.length)
addValues(hour12, true);
if (hour24.length)
addValues(hour24);
return valueParts.reduce((map, part) => {
map[part.type] = part.value;
return map;
}, {});
}
function minsToOffset(timeDiffInMins) {
const hours = String(Math.floor(Math.abs(timeDiffInMins / 60))).padStart(
2,
"0"
);
const mins = String(Math.abs(timeDiffInMins % 60)).padStart(2, "0");
const sign = timeDiffInMins < 0 ? "-" : "+";
return `${sign}${hours}${mins}`;
}
function offsetToMins(offset2) {
validOffset(offset2);
const [_, sign, hours, mins] = offset2.match(/([+-])([0-3][0-9])([0-6][0-9])/);
const offsetInMins = Number(hours) * 60 + Number(mins);
return sign === "+" ? offsetInMins : -offsetInMins;
}
function validOffset(offset2) {
const valid = /^([+-])[0-3][0-9]:?[0-6][0-9]$/.test(offset2);
if (!valid)
throw new Error(`Invalid offset: ${offset2}`);
return offset2;
}
function escapeTokens(str) {
return clockAgnostic.concat(clock24).concat(clock12).sort((a, b) => a[0].length > b[0].length ? 1 : -1).reduce((target, part) => {
return target.replace(part[0], `\\${part[0]}`);
}, str);
}
function isNumeric(part) {
return ["numeric", "2-digit"].includes(part.partValue);
}
function validate(parts2) {
let lastPart = void 0;
for (const part of parts2) {
if (part.partName === "literal" && !isNaN(parseFloat(part.partValue))) {
throw new Error(`Numbers in format (${part.partValue}).`);
}
if (lastPart && lastPart.partName !== "literal" && part.partName !== "literal") {
if (!(lastPart.token in fixedLength) && !(part.token in fixedLength) && !(isNumeric(lastPart) && part.token.toLowerCase() === "a")) {
throw new Error(
`Illegal adjacent tokens (${lastPart.token}, ${part.token})`
);
}
}
lastPart = part;
}
return parts2;
}
// src/ap.ts
function ap(ampm, locale) {
const l = dayPeriodMap.get(locale);
if (l && l[ampm])
return l[ampm];
const specimen = new Date(specDate);
specimen.setUTCHours(ampm === "am" ? 5 : 20);
const subparts = new Intl.DateTimeFormat(locale, {
timeStyle: "full",
timeZone: "UTC",
hour12: true
}).formatToParts(specimen).map(normStr);
const period = subparts.find((part) => part.type === "dayPeriod");
if (period) {
const localePeriods = l || {};
dayPeriodMap.set(
locale,
Object.assign(localePeriods, { [ampm]: period.value })
);
return period.value;
}
return ampm;
}
// src/applyOffset.ts
function applyOffset(dateInput, offset2 = "+0000") {
const d = date(dateInput);
const timeDiffInMins = offsetToMins(offset2);
return new Date(d.getTime() + timeDiffInMins * 1e3 * 60);
}
// src/deviceTZ.ts
function deviceTZ() {
return Intl.DateTimeFormat().resolvedOptions().timeZone;
}
// src/offset.ts
function relativeTime(d, timeZone) {
const utcParts = new Intl.DateTimeFormat("en-US", {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
timeZone,
hourCycle: "h23"
}).formatToParts(d).map(normStr);
const parts2 = {};
utcParts.forEach((part) => {
parts2[part.type] = part.value;
});
return /* @__PURE__ */ new Date(
`${parts2.year}-${parts2.month}-${parts2.day}T${parts2.hour}:${parts2.minute}:${parts2.second}Z`
);
}
function offset(utcTime, tzA = "UTC", tzB = "device") {
var _a;
tzB = tzB === "device" ? (_a = deviceTZ()) != null ? _a : "utc" : tzB;
const d = date(utcTime);
const timeA = relativeTime(d, tzA);
const timeB = relativeTime(d, tzB);
const timeDiffInMins = (timeB.getTime() - timeA.getTime()) / 1e3 / 60;
return minsToOffset(timeDiffInMins);
}
// src/tzDate.ts
function tzDate(inputDate, tz) {
const d = date(inputDate);
return applyOffset(d, offset(d, tz));
}
// src/dayOfYear.ts
function dayOfYear(inputDate) {
const d = date(inputDate);
return Math.round(
(new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0, 0).getTime() - new Date(d.getFullYear(), 0, 0).getTime()) / 864e5
);
}
// src/dayEnd.ts
function dayEnd(inputDate) {
const d = date(inputDate);
d.setHours(23, 59, 59, 999);
return d;
}
// src/dayStart.ts
function dayStart(inputDate) {
const d = date(inputDate);
d.setHours(0, 0, 0);
return d;
}
// src/parts.ts
function parts(format2, locale) {
if (styles.includes(format2) || typeof format2 === "object") {
return styleParts(format2, locale);
}
let f = format2;
let match = 0;
const testPattern = (pattern) => {
if (!pattern[2])
pattern[2] = new RegExp(`(.)?(${pattern[0]})`, "g");
if (pattern[2].test(f)) {
let didAdd = 0;
f = f.replace(pattern[2], (_, prefix, actualMatch) => {
if (prefix === "\\")
return actualMatch;
return `${typeof prefix === "string" ? prefix : ""}{!${didAdd++ ? match : match++}!}`;
});
return !!didAdd;
}
return false;
};
function validate2(patterns) {
const parts3 = patterns.map((part) => part.partName);
const deduped = new Set(parts3);
if (parts3.length > deduped.size) {
throw new Error(`Cannot reuse format tokens.`);
}
return patterns;
}
function createPart(hour12, [token, option, exp]) {
const partName = Object.keys(option)[0];
const partValue = option[partName];
return {
option,
partName,
partValue,
token,
pattern: exp,
hour12
};
}
const found24Patterns = clockAgnostic.filter(testPattern).concat(clock24.filter(testPattern)).map(createPart.bind(null, false));
const parts2 = validate2(
found24Patterns.concat(
clock12.filter(testPattern).map(createPart.bind(null, true))
)
);
const extractIndex = /^\{!(\d+)!\}$/;
return f.split(/(\{!\d+!\})/).map((match2) => {
const hasIndex = match2.match(extractIndex);
if (hasIndex) {
return parts2[Number(hasIndex[1])];
}
return {
option: { literal: match2 },
partName: "literal",
partValue: match2,
token: match2,
pattern: new RegExp(""),
hour12: false
};
}).filter((part) => !(part.partName === "literal" && part.partValue === ""));
}
function styleParts(format2, locale) {
const options = {
timeZone: "UTC"
};
if (typeof format2 === "string") {
options.dateStyle = format2;
} else {
if ("date" in format2)
options.dateStyle = format2.date;
if ("time" in format2)
options.timeStyle = format2.time;
}
const formatter = new Intl.DateTimeFormat(locale, options);
const segments = formatter.formatToParts(new Date(specDate)).map(normStr);
const hourTypeSegments = formatter.formatToParts(/* @__PURE__ */ new Date("1999-04-05T23:05:01.000Z")).map(normStr);
const hourPart = hourTypeSegments.find((segment) => segment.type === "hour");
const hourType = hourPart && hourPart.value === "23" ? 24 : 12;
return segments.map((part) => {
const partName = part.type;
const formatPattern = guessPattern(
part.type,
part.value,
locale,
part.type === "hour" ? hourType : void 0
);
if (formatPattern === void 0)
return;
const partValue = formatPattern[1][partName];
if (!partValue)
return;
if (!formatPattern[2])
formatPattern[2] = new RegExp(`${formatPattern[0]}`, "g");
return {
option: { [partName]: partValue },
partName,
partValue,
token: formatPattern[0],
pattern: formatPattern[2],
hour12: hourType === 12
};
}).filter((part) => !!part);
}
function guessPattern(partName, partValue, locale, hour) {
const l = partValue.length;
const n = !isNaN(Number(partValue));
let style;
switch (partName) {
case "year":
return l === 2 ? tokens.get("YY") : tokens.get("YYYY");
case "month":
if (n)
return l === 1 ? tokens.get("M") : tokens.get("MM");
style = partStyle(locale, partName, partValue);
switch (style) {
case "long":
return tokens.get("MMMM");
default:
return tokens.get("MMM");
}
case "day":
return l === 1 ? tokens.get("D") : tokens.get("DD");
case "weekday":
style = partStyle(locale, partName, partValue);
switch (style) {
case "narrow":
return tokens.get("d");
case "short":
return tokens.get("ddd");
default:
return tokens.get("dddd");
}
case "hour":
if (hour === 12)
return l === 1 ? tokens.get("h") : tokens.get("hh");
return l === 1 ? tokens.get("H") : tokens.get("HH");
case "minute":
return l === 1 ? tokens.get("m") : tokens.get("mm");
case "second":
return l === 1 ? tokens.get("s") : tokens.get("ss");
case "dayPeriod":
return /^[A-Z]+$/u.test(partValue) ? tokens.get("A") : tokens.get("a");
case "literal":
return [partValue, { literal: partValue }, new RegExp("")];
case "timeZoneName":
const offset2 = partValue.split("-");
return offset2.length === 2 && offset2[1].length === 4 ? tokens.get("ZZ") : tokens.get("Z");
default:
return void 0;
}
}
function partStyle(locale, part, value) {
if (!memoParts.has(locale)) {
const date2 = new Date(specDate);
const weekdays = [3, 8, 9, 7, 6, 4, 3];
const parts2 = ["weekday", "month", "dayPeriod"];
const partStyles = ["long", "short", "narrow"];
const formats2 = {};
for (let i = 0; i < 12; i++) {
date2.setMonth(0 + i);
if (i in weekdays)
date2.setDate(weekdays[i]);
date2.setUTCHours(8 + i);
for (const style of partStyles) {
const segments = new Intl.DateTimeFormat(
locale,
parts2.reduce(
(options, part2) => Object.assign(options, { [part2]: style }),
{ hour12: true, timeZone: "UTC" }
)
).formatToParts(date2).map(normStr);
if (style === "long" || style === "short") {
const genitiveFormattedParts = new Intl.DateTimeFormat(locale, {
dateStyle: style === "short" ? "medium" : "long",
timeZone: "UTC"
}).formatToParts(date2).map(normStr);
const genitiveMonth = genitiveFormattedParts.find(
(part2) => part2.type === "month"
);
const index = segments.findIndex((part2) => part2.type === "month");
if (index > -1 && genitiveMonth)
segments[index] = genitiveMonth;
}
segments.forEach((part2) => {
if (part2.type === "literal")
return;
const type = part2.type;
formats2[type] = Object.assign(formats2[type] || {}, {
[part2.value]: style
});
});
}
}
memoParts.set(locale, formats2);
}
const formats = memoParts.get(locale);
return formats ? formats[part][value] : void 0;
}
// src/removeOffset.ts
function removeOffset(dateInput, offset2 = "+0000") {
const positive = offset2.slice(0, 1) === "+";
return applyOffset(
dateInput,
offset2.replace(positive ? "+" : "-", positive ? "-" : "+")
);
}
// src/deviceLocale.ts
function deviceLocale() {
return Intl.DateTimeFormat().resolvedOptions().locale;
}
// src/format.ts
function format(inputDateOrOptions, format2 = "long", locale = "device", genitive = false, partFilter) {
let tz, forceOffset;
if (typeof inputDateOrOptions === "object" && !(inputDateOrOptions instanceof Date)) {
;
({
date: inputDateOrOptions,
format: format2,
locale,
genitive,
partFilter,
tz
} = inputDateOrOptions);
}
if (format2 === "ISO8601")
return date(inputDateOrOptions).toISOString();
if (tz) {
forceOffset = offset(inputDateOrOptions, "utc", tz);
}
tz != null ? tz : tz = deviceTZ();
if ((tz == null ? void 0 : tz.toLowerCase()) !== "utc") {
inputDateOrOptions = removeOffset(
inputDateOrOptions,
offset(inputDateOrOptions, tz, "utc")
);
}
if (!locale || locale === "device") {
locale = deviceLocale();
}
return fill(
inputDateOrOptions,
parts(format2, locale).filter(partFilter != null ? partFilter : () => true),
locale,
genitive,
forceOffset
).map((p) => p.value).join("");
}
// src/formatStr.ts
function formatStr(format2, locale = "en", escapeLiterals = false, filterParts = () => true) {
return parts(format2, locale).filter(filterParts).reduce(
(f, p) => f += escapeLiterals && p.partName === "literal" ? escapeTokens(p.token) : p.token,
""
).normalize("NFKC");
}
// src/fourDigitYear.ts
function fourDigitYear(value) {
const y = (/* @__PURE__ */ new Date()).getFullYear();
const currentYear = y % 100;
const century = Math.floor(y / 100);
const parsedYear = Number(value);
return (century + (parsedYear > currentYear + 20 ? -1 : 0)) * 100 + parsedYear;
}
// src/hourEnd.ts
function hourEnd(inputDate) {
const d = date(inputDate);
d.setMinutes(59, 59, 999);
return d;
}
// src/hourStart.ts
function hourStart(inputDate) {
const d = date(inputDate);
d.setMinutes(0, 0);
return d;
}
// src/minuteEnd.ts
function minuteEnd(inputDate) {
const d = date(inputDate);
d.setSeconds(59, 999);
return d;
}
// src/minuteStart.ts
function minuteStart(inputDate) {
const d = date(inputDate);
d.setSeconds(0);
return d;
}
// src/monthStart.ts
function monthStart(inputDate) {
const d = date(inputDate);
d.setDate(1);
d.setHours(0, 0, 0);
return d;
}
// src/yearDays.ts
function yearDays(inputDate) {
const d = date(inputDate);
return (new Date(d.getFullYear() + 1, 0, 0).getTime() - new Date(d.getFullYear(), 0, 0).getTime()) / 864e5;
}
// src/nearestDay.ts
function nearestDay(inputDate, search, constraint = 7) {
let increments;
let decrements;
const d = date(inputDate);
switch (constraint) {
case "month":
decrements = d.getDate();
increments = monthDays(d) - d.getDate();
break;
case "week":
decrements = d.getDay() + 1;
increments = 6 - d.getDay();
break;
case "year":
const total = yearDays(d);
const day = dayOfYear(d);
decrements = day;
increments = total - day;
break;
default:
increments = decrements = constraint;
}
for (let i = 0; i <= increments || i < decrements; i++) {
if (i <= increments) {
const next = addDay(d, i);
if (search(next))
return next;
}
if (i && i <= decrements) {
const prev = addDay(d, -i);
if (search(prev))
return prev;
}
}
return null;
}
// src/range.ts
function range(token, locale = "en", genitive = false) {
const r = (n, c) => Array(n).fill("").map((_, i) => `${c(i)}`);
if (token === "M")
return r(12, (i) => i + 1);
if (token === "MM")
return r(12, (i) => {
const m = i + 1;
return m < 10 ? `0${m}` : m;
});
if (token.startsWith("M"))
return range("MM").map(
(m) => format(`2000-${m}-05`, token, locale, genitive)
);
if (token.startsWith("d"))
return r(7, (i) => `0${i + 2}`).map(
(d) => format(`2022-10-${d}`, token, locale)
);
if (token === "a")
return [ap("am", locale).toLowerCase(), ap("pm", locale).toLowerCase()];
if (token === "A")
return [ap("am", locale).toUpperCase(), ap("pm", locale).toUpperCase()];
if (token.startsWith("Y")) {
const year = (/* @__PURE__ */ new Date()).getFullYear();
return r(120, (i) => i + 1).reduce(
(ranges, i) => {
if (i !== "120")
ranges.push(format(`${year + Number(i)}-06-06`, token, locale));
ranges.unshift(format(`${year - Number(i)}-06-06`, token, locale));
return ranges;
},
[format(`${year}-06-06`, token, locale)]
);
}
if (token.startsWith("D"))
return r(31, (i) => `${token === "DD" && i < 9 ? "0" : ""}${i + 1}`);
if (token.startsWith("H"))
return r(24, (i) => `${token === "HH" && i < 10 ? "0" : ""}${i}`);
if (token.startsWith("h"))
return r(12, (i) => `${token === "hh" && i < 9 ? "0" : ""}${i + 1}`);
if (token.startsWith("m") || token.startsWith("s"))
return r(60, (i) => `${token.length > 1 && i < 10 ? "0" : ""}${i}`);
return [];
}
// src/parse.ts
function parse(dateStrOrOptions, format2 = "ISO8601", locale = "device") {
let partFilter = () => true;
let dateStr;
let dateOverflow = "backward";
if (typeof dateStrOrOptions === "object") {
;
({
date: dateStr,
format: format2 = "ISO8601",
locale = "device",
dateOverflow = "backward",
partFilter = () => true
} = dateStrOrOptions);
} else {
dateStr = dateStrOrOptions;
}
if (!dateStr)
throw new Error("parse() requires a date string.");
const invalid = () => {
throw new Error(
`Date (${dateStr}) does not match format (${formatStr(format2, locale)})`
);
};
if (format2 === "ISO8601")
return date(dateStr);
const genitive = styles.includes(format2) || typeof format2 === "object";
const formatParts = validate(parts(format2, locale).filter(partFilter));
if (!formatParts.length)
throw new Error("parse() requires a pattern.");
let parsedParts;
try {
parsedParts = parseParts(dateStr, formatParts);
} catch {
return invalid();
}
const now = /* @__PURE__ */ new Date();
const parsed = /* @__PURE__ */ new Map([
["YYYY", now.getFullYear()],
["MM", now.getMonth() + 1],
["DD", now.getDate()],
["HH", 0],
["mm", 0],
["ss", 0]
]);
let a = null;
let offset2 = "";
parsedParts.forEach((part) => {
if (part.partName === "literal")
return;
if (part.token === part.value)
return invalid();
const v = Number(part.value);
if (parsed.has(part.token)) {
parsed.set(part.token, v);
} else if (part.token === "YY") {
parsed.set("YYYY", fourDigitYear(part.value));
} else {
const t = part.token;
if (t.startsWith("d")) {
return;
} else if (t === "D") {
parsed.set("DD", v);
} else if (t === "H" || t.startsWith("h")) {
parsed.set("HH", v);
} else if (t === "M") {
parsed.set("MM", v);
} else if (t === "a" || t === "A") {
a = part.value.toLowerCase() === ap("am", locale).toLowerCase();
} else if (t === "Z") {
offset2 = validOffset(part.value);
} else {
const values = range(t, locale, genitive);
const index = values.indexOf(part.value);
if (index !== -1) {
switch (t) {
case "MMM":
case "MMMM":
parsed.set("MM", index + 1);
break;
}
}
}
}
});
let hours = parsed.get("HH") || 0;
if (a === false) {
hours += hours === 12 ? 0 : 12;
parsed.set("HH", hours === 24 ? 0 : hours);
} else if (a === true && hours === 12) {
parsed.set("HH", 0);
}
parsed.set("MM", (parsed.get("MM") || 1) - 1);
let [Y, M, D, h, m, s] = Array.from(parsed.values());
const maxDaysInMonth = monthDays(/* @__PURE__ */ new Date(`${four(Y)}-${two(M + 1)}-10`));
if (maxDaysInMonth < D && dateOverflow === "throw")
throw new Error(`Invalid date ${four(Y)}-${two(M + 1)}-${two(D)}`);
D = dateOverflow === "backward" ? Math.min(D, maxDaysInMonth) : D;
const isoString = `${four(Y)}-${two(M + 1)}-${two(D)}T${two(h)}:${two(
m
)}:${two(s)}${offset2}`;
const d = new Date(isoString);
if (isFinite(+d))
return d;
return invalid();
}
function parseParts(dateStr, formatParts) {
let i = 0;
const advance = (parts2) => [
parts2[i++],
parts2[i]
];
let pos = 0;
const parsed = [];
let n = void 0;
do {
const [current, next] = advance(formatParts);
n = next;
let len = 1;
if (current.partName === "literal") {
len = current.partValue.length;
} else if (current.partName === "timeZoneName") {
len = fixedLengthByOffset(dateStr.substring(pos));
} else if (current.token in fixedLength) {
len = fixedLength[current.token];
} else if (next) {
if (next.partName === "literal") {
len = dateStr.indexOf(next.partValue, pos) - pos;
if (len < 0)
throw new Error();
} else if (next.partName === "dayPeriod") {
for (let i2 = 1; i2 <= 4; i2++) {
if (isNaN(Number(dateStr.charAt(pos + i2)))) {
len = i2;
break;
}
}
} else {
const nextChar = dateStr.substring(pos).search(/\d/);
if (nextChar !== -1)
len = pos + nextChar;
}
} else {
len = dateStr.length;
}
parsed.push({ ...current, value: dateStr.substring(pos, pos + len) });
pos += len;
} while (n);
return parsed;
}
// src/sameDay.ts
function sameDay(inputDateA, inputDateB) {
const a = date(inputDateA);
const b = date(inputDateB);
return a.getDate() === b.getDate() && a.getMonth() === b.getMonth() && a.getFullYear() === b.getFullYear();
}
// src/sameSecond.ts
function sameSecond(inputDateA, inputDateB) {
const a = date(inputDateA);
const b = date(inputDateB);
return a.getSeconds() === b.getSeconds();
}
// src/sameMinute.ts
function sameMinute(inputDateA, inputDateB) {
const a = date(inputDateA);
const b = date(inputDateB);
return a.getMinutes() === b.getMinutes();
}
// src/sameHour.ts
function sameHour(inputDateA, inputDateB) {
const a = date(inputDateA);
const b = date(inputDateB);
return a.getHours() === b.getHours();
}
// src/sameYear.ts
function sameYear(inputDateA, inputDateB) {
const a = date(inputDateA);
const b = date(inputDateB);
return a.getFullYear() === b.getFullYear();
}
// src/weekStart.ts
function weekStart(inputDate, startOfWeekDay = 0) {
const d = date(inputDate);
let diff = startOfWeekDay - d.getDay();
if (diff > 0)
diff = diff - 7;
d.setDate(d.getDate() + diff);
d.setHours(0, 0, 0);
return d;
}
// src/weekEnd.ts
function weekEnd(inputDate, startOfWeekDay = 0) {
const d = weekStart(inputDate, startOfWeekDay);
d.setDate(d.getDate() + 6);
d.setHours(23, 59, 59);
return d;
}
// src/yearStart.ts
function yearStart(inputDate) {
const d = date(inputDate);
d.setMonth(0);
d.setDate(1);
d.setHours(0, 0, 0);
return d;
}
// src/yearEnd.ts
function yearEnd(inputDate) {
const d = date(inputDate);
d.setMonth(11);
d.setDate(31);
d.setHours(23, 59, 59, 999);
return d;
}
// src/isBefore.ts
function isBefore(inputDate, dateToCompare) {
const _date = date(inputDate);
const _dateToCompare = date(dateToCompare);
return +_date < +_dateToCompare;
}
// src/isAfter.ts
function isAfter(inputDate, dateToCompare) {
const _date = date(inputDate);
const _dateToCompare = date(dateToCompare);
return +_date > +_dateToCompare;
}
// src/isEqual.ts
function isEqual(dateLeft, dateRight) {
const _dateLeft = date(dateLeft);
const _dateRight = date(dateRight);
return +_dateLeft === +_dateRight;
}
// src/index.ts
import { addDay } from "./addDay.mjs";
import { addMonth } from "./addMonth.mjs";
import { addYear } from "./addYear.mjs";
import { addHour } from "./addHour.mjs";
import { addMinute } from "./addMinute.mjs";
import { addSecond } from "./addSecond.mjs";
import { ap } from "./ap.mjs";
import { applyOffset } from "./applyOffset.mjs";
import { date } from "./date.mjs";
import { tzDate } from "./tzDate.mjs";
import { dayOfYear } from "./dayOfYear.mjs";
import { dayEnd } from "./dayEnd.mjs";
import { dayStart } from "./dayStart.mjs";
import { format } from "./format.mjs";
import { formatStr } from "./formatStr.mjs";
import { fourDigitYear } from "./fourDigitYear.mjs";
import { hourEnd } from "./hourEnd.mjs";
import { hourStart } from "./hourStart.mjs";
import { iso8601 } from "./iso8601.mjs";
import { minuteEnd } from "./minuteEnd.mjs";
import { minuteStart } from "./minuteStart.mjs";
import { monthDays } from "./monthDays.mjs";
import { monthEnd } from "./monthEnd.mjs";
import { monthStart } from "./monthStart.mjs";
import { nearestDay } from "./nearestDay.mjs";
import { offset } from "./offset.mjs";
import { parse } from "./parse.mjs";
import { parseParts } from "./parse.mjs";
import { parts } from "./parts.mjs";
import { range } from "./range.mjs";
import { removeOffset } from "./removeOffset.mjs";
import { sameDay } from "./sameDay.mjs";
import { sameSecond } from "./sameSecond.mjs";
import { sameMinute } from "./sameMinute.mjs";
import { sameHour } from "./sameHour.mjs";
import { sameYear } from "./sameYear.mjs";
import { weekEnd } from "./weekEnd.mjs";
import { weekStart } from "./weekStart.mjs";
import { yearDays } from "./yearDays.mjs";
import { yearStart } from "./yearStart.mjs";
import { yearEnd } from "./yearEnd.mjs";
import { isBefore } from "./isBefore.mjs";
import { isAfter } from "./isAfter.mjs";
import { isEqual } from "./isEqual.mjs";
export * from "./types.mjs";
import { diffMilliseconds } from "./diffMilliseconds.mjs";
import { diffSeconds } from "./diffSeconds.mjs";
import { diffMinutes } from "./diffMinutes.mjs";
import { diffHours } from "./diffHours.mjs";
import { diffDays } from "./diffDays.mjs";
import { diffWeeks } from "./diffWeeks.mjs";
import { diffMonths } from "./diffMonths.mjs";
import { diffYears } from "./diffYears.mjs";
export {

@@ -1071,2 +68,10 @@ addDay,

dayStart,
diffDays,
diffHours,
diffMilliseconds,
diffMinutes,
diffMonths,
diffSeconds,
diffWeeks,
diffYears,
format,

@@ -1073,0 +78,0 @@ formatStr,

{
"name": "@formkit/tempo",
"version": "0.0.19",
"version": "0.1.0",
"description": "The easiest way to work with dates in JavaScript and TypeScript.",

@@ -8,2 +8,4 @@ "type": "module",

"types": "dist/index.d.cts",
"browser": "dist/bundle.mjs",
"unpkg": "dist/bundle.mjs",
"exports": {

@@ -18,2 +20,6 @@ ".": {

"default": "./dist/index.cjs"
},
"browser": {
"types": "./dist/bundle.d.ts",
"default": "./dist/bundle.mjs"
}

@@ -42,2 +48,3 @@ }

"bytes-iec": "^3.1.1",
"esbuild-plugin-file-path-extensions": "^2.0.0",
"publint": "^0.2.7",

@@ -44,0 +51,0 @@ "size-limit": "^11.0.2",

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display