@formkit/tempo 1.2.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bundle.d.ts +826 -0
- package/dist/bundle.mjs +33 -23
- package/dist/bundle.mjs.map +1 -1
- package/dist/common.mjs +3 -2
- package/dist/common.mjs.map +1 -1
- package/dist/dayOfYear.mjs +1 -3
- package/dist/dayOfYear.mjs.map +1 -1
- package/dist/diffDays.mjs +5 -7
- package/dist/diffDays.mjs.map +1 -1
- package/dist/diffMonths.mjs +4 -1
- package/dist/diffMonths.mjs.map +1 -1
- package/dist/diffWeeks.d.ts +5 -5
- package/dist/diffWeeks.mjs +5 -6
- package/dist/diffWeeks.mjs.map +1 -1
- package/dist/hourEnd.mjs +5 -0
- package/dist/hourEnd.mjs.map +1 -1
- package/dist/hourStart.mjs +4 -0
- package/dist/hourStart.mjs.map +1 -1
- package/dist/index.cjs +33 -23
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/minuteEnd.mjs +3 -1
- package/dist/minuteEnd.mjs.map +1 -1
- package/dist/minuteStart.mjs +1 -1
- package/dist/minuteStart.mjs.map +1 -1
- package/dist/nearestDay.mjs +4 -4
- package/dist/nearestDay.mjs.map +1 -1
- package/package.json +1 -1
package/dist/common.mjs
CHANGED
|
@@ -214,8 +214,9 @@ function isNumeric(part) {
|
|
|
214
214
|
}
|
|
215
215
|
function validate(parts) {
|
|
216
216
|
let lastPart = void 0;
|
|
217
|
-
|
|
218
|
-
|
|
217
|
+
const knownWidth = (p) => !p || p.partName === "literal" || p.token in fixedLength;
|
|
218
|
+
for (const [i, part] of parts.entries()) {
|
|
219
|
+
if (part.partName === "literal" && !isNaN(parseFloat(part.partValue)) && !(knownWidth(parts[i - 1]) && knownWidth(parts[i + 1]))) {
|
|
219
220
|
throw new Error(`Numbers in format (${part.partValue}).`);
|
|
220
221
|
}
|
|
221
222
|
if (lastPart && lastPart.partName !== "literal" && part.partName !== "literal") {
|
package/dist/common.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"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 MaybeDateInput,\n ExtendedPartTypes,\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 * Fractional seconds patterns.\n */\nexport const fractionalSeconds: FormatPattern[] = [\n [\"SSS\", { fractionalSecond: \"3-digit\" }],\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 * Determines the length of a timezone offset string.\n * Supports offsets with optional seconds component.\n */\nexport function fixedLengthByOffset(offsetString: string): 9 | 8 | 6 | 5 {\n // starts with [+-]xx:xx:xx (9 chars, Z format with seconds)\n if (/^[+-]\\d{2}:\\d{2}:\\d{2}/.test(offsetString)) {\n return 9\n }\n\n // starts with [+-]xxxxxx (8 chars, ZZ format with seconds)\n if (/^[+-]\\d{6}/.test(offsetString)) {\n return 8\n }\n\n // starts with [+-]xx:xx (6 chars, Z format)\n if (/^[+-]\\d{2}:\\d{2}/.test(offsetString)) {\n return 6\n }\n\n // starts with [+-]xxxx (5 chars, ZZ format)\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, ...fractionalSeconds].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> = [\"full\", \"long\", \"medium\", \"short\"]\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(4, \"0\")\n\n/**\n * Normalizes a given part to NFKC.\n * @param part - The part to normalize.\n */\nexport function normStr(part: Intl.DateTimeFormatPart): Intl.DateTimeFormatPart {\n if (part.type === \"literal\") {\n part.value = part.value.normalize(\"NFKC\")\n }\n return part\n}\n\nconst zeros: Record<string, string> = {}\n\n/**\n * The zero digit in a locale’s default numbering system (e.g. \"০\" for bn), so\n * padded values never mix Latin and native digits.\n * @param locale - The locale to get the zero digit for.\n */\nfunction localeZero(locale: string): string {\n return (\n zeros[locale] || (zeros[locale] = new Intl.NumberFormat(locale).format(0))\n )\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: MaybeDateInput,\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 `${localeZero(locale)}${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 === \"fractionalSecond\") {\n return String(d.getUTCMilliseconds()).padStart(3, \"0\")\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: MaybeDateInput,\n parts: Part[],\n locale: string,\n genitive = false\n): Record<ExtendedPartTypes, 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 // Use Intl.Locale to merge the hourCycle extension into the locale tag.\n // Plain string concatenation (e.g. `${locale}-u-hc-h23`) produces an\n // invalid BCP 47 tag when the locale already contains a Unicode extension\n // block (e.g. \"ar-u-nu-arab\"), because a tag may only have one \"-u-\" block.\n // Intl.Locale merges extensions correctly into a single \"-u-\" subtag.\n const preciseLocale = new Intl.Locale(locale, {\n hourCycle: hour12 ? \"h12\" : \"h23\",\n }).toString()\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((p) => p.type === part.partName)\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 as ExtendedPartTypes] = part.value\n return map\n }, {} as Record<ExtendedPartTypes, string>)\n}\n\n/**\n * Converts total seconds to an ISO8601 compatible offset (+04:00 or +0400).\n * Only includes seconds in output if they are non-zero.\n * @param totalSecs - The total offset in seconds (can be negative).\n * @param token - \"Z\" for +HH:mm[:ss] or \"ZZ\" for +HHmm[ss]\n */\nexport function secsToOffset(totalSecs: number, token: string = \"Z\"): string {\n const sign = totalSecs < 0 ? \"-\" : \"+\"\n const absSecs = Math.abs(totalSecs)\n const hours = String(Math.floor(absSecs / 3600)).padStart(2, \"0\")\n const mins = String(Math.floor((absSecs % 3600) / 60)).padStart(2, \"0\")\n const secs = Math.round(absSecs % 60)\n\n if (token === \"ZZ\") {\n return secs === 0\n ? `${sign}${hours}${mins}`\n : `${sign}${hours}${mins}${String(secs).padStart(2, \"0\")}`\n }\n return secs === 0\n ? `${sign}${hours}:${mins}`\n : `${sign}${hours}:${mins}:${String(secs).padStart(2, \"0\")}`\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(timeDiffInMins: number, token: string = \"Z\"): string {\n return secsToOffset(timeDiffInMins * 60, token)\n}\n\n/**\n * Converts an offset (-05:32:11 or -053211) to total seconds.\n * Supports offsets with optional seconds component.\n * @param offset - The offset to convert to seconds.\n * @param token - The timezone token format.\n */\nexport function offsetToSecs(offset: string, token: TimezoneToken): number {\n validOffset(offset, token)\n const match = offset.match(/([+-])([0-3][0-9]):?([0-5][0-9])(?::?([0-5][0-9]))?/)!\n const [_, sign, hours, mins, secs = \"0\"] = match\n const totalSecs = Number(hours) * 3600 + Number(mins) * 60 + Number(secs)\n return sign === \"+\" ? totalSecs : -totalSecs\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 return Math.round(offsetToSecs(offset, token) / 60)\n}\n\n/**\n * Validates that an offset is valid according to the format:\n * [+-]HH:mm or [+-]HH:mm:ss (Z token)\n * [+-]HHmm or [+-]HHmmss (ZZ token)\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-5][0-9](?::[0-5][0-9])?$/.test(offset)\n case \"ZZ\":\n return /^([+-])[0-3][0-9][0-5][0-9](?:[0-5][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 .concat(fractionalSeconds)\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 (lastPart && lastPart.partName !== \"literal\" && part.partName !== \"literal\") {\n if (\n !(lastPart.token in fixedLength) &&\n !(part.token in fixedLength) &&\n !(isNumeric(lastPart) && part.token.toLowerCase() === \"a\") &&\n lastPart.token !== \"SSS\" // SSS can be followed by anything (greedy digit consumer)\n ) {\n throw new Error(`Illegal adjacent tokens (${lastPart.token}, ${part.token})`)\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}\n"],"mappings":";AAAA,SAAS,YAAY;AACrB,SAAS,UAAU;AAgBZ,IAAM,WAAW;AAKjB,IAAM,YAAuC,oBAAI,IAAI;AAKrD,IAAM,gBAAiC;AAAA,EAC5C,CAAC,QAAQ,EAAE,MAAM,UAAU,CAAC;AAAA,EAC5B,CAAC,MAAM,EAAE,MAAM,UAAU,CAAC;AAAA,EAC1B,CAAC,QAAQ,EAAE,OAAO,OAAO,CAAC;AAAA,EAC1B,CAAC,OAAO,EAAE,OAAO,QAAQ,CAAC;AAAA,EAC1B,CAAC,MAAM,EAAE,OAAO,UAAU,CAAC;AAAA,EAC3B,CAAC,KAAK,EAAE,OAAO,UAAU,CAAC;AAAA,EAC1B,CAAC,MAAM,EAAE,KAAK,UAAU,CAAC;AAAA,EACzB,CAAC,KAAK,EAAE,KAAK,UAAU,CAAC;AAAA,EACxB,CAAC,QAAQ,EAAE,SAAS,OAAO,CAAC;AAAA,EAC5B,CAAC,OAAO,EAAE,SAAS,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GAAG,MAAO,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,SAAS,IAAI,EAAG,EACnD,OAAO,CAAC,QAAQ,SAAS;AACxB,WAAO,OAAO,QAAQ,KAAK,CAAC,GAAG,KAAK,KAAK,CAAC,CAAC,EAAE;AAAA,EAC/C,GAAG,GAAG;AACV;AAMO,SAAS,UAAU,MAAY;AACpC,SAAO,CAAC,WAAW,SAAS,EAAE,SAAS,KAAK,SAAS;AACvD;AAMO,SAAS,SAAS,OAA+B;AACtD,MAAI,WAA6B;AACjC,aAAW,QAAQ,OAAO;AACxB,QAAI,KAAK,aAAa,aAAa,CAAC,MAAM,WAAW,KAAK,SAAS,CAAC,GAAG;AACrE,YAAM,IAAI,MAAM,sBAAsB,KAAK,SAAS,IAAI;AAAA,IAC1D;AACA,QAAI,YAAY,SAAS,aAAa,aAAa,KAAK,aAAa,WAAW;AAC9E,UACE,EAAE,SAAS,SAAS,gBACpB,EAAE,KAAK,SAAS,gBAChB,EAAE,UAAU,QAAQ,KAAK,KAAK,MAAM,YAAY,MAAM,QACtD,SAAS,UAAU,OACnB;AACA,cAAM,IAAI,MAAM,4BAA4B,SAAS,KAAK,KAAK,KAAK,KAAK,GAAG;AAAA,MAC9E;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"]}
|
|
1
|
+
{"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 MaybeDateInput,\n ExtendedPartTypes,\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 * Fractional seconds patterns.\n */\nexport const fractionalSeconds: FormatPattern[] = [\n [\"SSS\", { fractionalSecond: \"3-digit\" }],\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 * Determines the length of a timezone offset string.\n * Supports offsets with optional seconds component.\n */\nexport function fixedLengthByOffset(offsetString: string): 9 | 8 | 6 | 5 {\n // starts with [+-]xx:xx:xx (9 chars, Z format with seconds)\n if (/^[+-]\\d{2}:\\d{2}:\\d{2}/.test(offsetString)) {\n return 9\n }\n\n // starts with [+-]xxxxxx (8 chars, ZZ format with seconds)\n if (/^[+-]\\d{6}/.test(offsetString)) {\n return 8\n }\n\n // starts with [+-]xx:xx (6 chars, Z format)\n if (/^[+-]\\d{2}:\\d{2}/.test(offsetString)) {\n return 6\n }\n\n // starts with [+-]xxxx (5 chars, ZZ format)\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, ...fractionalSeconds].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> = [\"full\", \"long\", \"medium\", \"short\"]\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(4, \"0\")\n\n/**\n * Normalizes a given part to NFKC.\n * @param part - The part to normalize.\n */\nexport function normStr(part: Intl.DateTimeFormatPart): Intl.DateTimeFormatPart {\n if (part.type === \"literal\") {\n part.value = part.value.normalize(\"NFKC\")\n }\n return part\n}\n\nconst zeros: Record<string, string> = {}\n\n/**\n * The zero digit in a locale’s default numbering system (e.g. \"০\" for bn), so\n * padded values never mix Latin and native digits.\n * @param locale - The locale to get the zero digit for.\n */\nfunction localeZero(locale: string): string {\n return (\n zeros[locale] || (zeros[locale] = new Intl.NumberFormat(locale).format(0))\n )\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: MaybeDateInput,\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 `${localeZero(locale)}${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 === \"fractionalSecond\") {\n return String(d.getUTCMilliseconds()).padStart(3, \"0\")\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: MaybeDateInput,\n parts: Part[],\n locale: string,\n genitive = false\n): Record<ExtendedPartTypes, 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 // Use Intl.Locale to merge the hourCycle extension into the locale tag.\n // Plain string concatenation (e.g. `${locale}-u-hc-h23`) produces an\n // invalid BCP 47 tag when the locale already contains a Unicode extension\n // block (e.g. \"ar-u-nu-arab\"), because a tag may only have one \"-u-\" block.\n // Intl.Locale merges extensions correctly into a single \"-u-\" subtag.\n const preciseLocale = new Intl.Locale(locale, {\n hourCycle: hour12 ? \"h12\" : \"h23\",\n }).toString()\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((p) => p.type === part.partName)\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 as ExtendedPartTypes] = part.value\n return map\n }, {} as Record<ExtendedPartTypes, string>)\n}\n\n/**\n * Converts total seconds to an ISO8601 compatible offset (+04:00 or +0400).\n * Only includes seconds in output if they are non-zero.\n * @param totalSecs - The total offset in seconds (can be negative).\n * @param token - \"Z\" for +HH:mm[:ss] or \"ZZ\" for +HHmm[ss]\n */\nexport function secsToOffset(totalSecs: number, token: string = \"Z\"): string {\n const sign = totalSecs < 0 ? \"-\" : \"+\"\n const absSecs = Math.abs(totalSecs)\n const hours = String(Math.floor(absSecs / 3600)).padStart(2, \"0\")\n const mins = String(Math.floor((absSecs % 3600) / 60)).padStart(2, \"0\")\n const secs = Math.round(absSecs % 60)\n\n if (token === \"ZZ\") {\n return secs === 0\n ? `${sign}${hours}${mins}`\n : `${sign}${hours}${mins}${String(secs).padStart(2, \"0\")}`\n }\n return secs === 0\n ? `${sign}${hours}:${mins}`\n : `${sign}${hours}:${mins}:${String(secs).padStart(2, \"0\")}`\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(timeDiffInMins: number, token: string = \"Z\"): string {\n return secsToOffset(timeDiffInMins * 60, token)\n}\n\n/**\n * Converts an offset (-05:32:11 or -053211) to total seconds.\n * Supports offsets with optional seconds component.\n * @param offset - The offset to convert to seconds.\n * @param token - The timezone token format.\n */\nexport function offsetToSecs(offset: string, token: TimezoneToken): number {\n validOffset(offset, token)\n const match = offset.match(/([+-])([0-3][0-9]):?([0-5][0-9])(?::?([0-5][0-9]))?/)!\n const [_, sign, hours, mins, secs = \"0\"] = match\n const totalSecs = Number(hours) * 3600 + Number(mins) * 60 + Number(secs)\n return sign === \"+\" ? totalSecs : -totalSecs\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 return Math.round(offsetToSecs(offset, token) / 60)\n}\n\n/**\n * Validates that an offset is valid according to the format:\n * [+-]HH:mm or [+-]HH:mm:ss (Z token)\n * [+-]HHmm or [+-]HHmmss (ZZ token)\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-5][0-9](?::[0-5][0-9])?$/.test(offset)\n case \"ZZ\":\n return /^([+-])[0-3][0-9][0-5][0-9](?:[0-5][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 .concat(fractionalSeconds)\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 // A literal containing digits is only unambiguous to parse when the parts\n // around it have a known width: fixed-length tokens (YYYY, MM, DD…), other\n // literals, or the start/end of the format. E.g. \"YYYY-MM-01\" is fine, but\n // \"M01D\" is not (formkit/formkit#1134).\n const knownWidth = (p?: Part) =>\n !p || p.partName === \"literal\" || p.token in fixedLength\n for (const [i, part] of parts.entries()) {\n if (\n part.partName === \"literal\" &&\n !isNaN(parseFloat(part.partValue)) &&\n !(knownWidth(parts[i - 1]) && knownWidth(parts[i + 1]))\n ) {\n throw new Error(`Numbers in format (${part.partValue}).`)\n }\n if (lastPart && lastPart.partName !== \"literal\" && part.partName !== \"literal\") {\n if (\n !(lastPart.token in fixedLength) &&\n !(part.token in fixedLength) &&\n !(isNumeric(lastPart) && part.token.toLowerCase() === \"a\") &&\n lastPart.token !== \"SSS\" // SSS can be followed by anything (greedy digit consumer)\n ) {\n throw new Error(`Illegal adjacent tokens (${lastPart.token}, ${part.token})`)\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}\n"],"mappings":";AAAA,SAAS,YAAY;AACrB,SAAS,UAAU;AAgBZ,IAAM,WAAW;AAKjB,IAAM,YAAuC,oBAAI,IAAI;AAKrD,IAAM,gBAAiC;AAAA,EAC5C,CAAC,QAAQ,EAAE,MAAM,UAAU,CAAC;AAAA,EAC5B,CAAC,MAAM,EAAE,MAAM,UAAU,CAAC;AAAA,EAC1B,CAAC,QAAQ,EAAE,OAAO,OAAO,CAAC;AAAA,EAC1B,CAAC,OAAO,EAAE,OAAO,QAAQ,CAAC;AAAA,EAC1B,CAAC,MAAM,EAAE,OAAO,UAAU,CAAC;AAAA,EAC3B,CAAC,KAAK,EAAE,OAAO,UAAU,CAAC;AAAA,EAC1B,CAAC,MAAM,EAAE,KAAK,UAAU,CAAC;AAAA,EACzB,CAAC,KAAK,EAAE,KAAK,UAAU,CAAC;AAAA,EACxB,CAAC,QAAQ,EAAE,SAAS,OAAO,CAAC;AAAA,EAC5B,CAAC,OAAO,EAAE,SAAS,QAAQ,CAAC;AAAA,EAC5B,CAAC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|
|
3
3
|
function dayOfYear(inputDate) {
|
|
4
4
|
const d = date(inputDate);
|
|
5
|
-
return
|
|
6
|
-
(new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0, 0).getTime() - new Date(d.getFullYear(), 0, 0).getTime()) / 864e5
|
|
7
|
-
);
|
|
5
|
+
return (Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()) - Date.UTC(d.getFullYear(), 0, 0)) / 864e5;
|
|
8
6
|
}
|
|
9
7
|
export {
|
|
10
8
|
dayOfYear
|
package/dist/dayOfYear.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/dayOfYear.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { MaybeDateInput } 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 or nothing for the current day.\n */\nexport function dayOfYear(inputDate?: MaybeDateInput): number {\n const d = date(inputDate)\n return
|
|
1
|
+
{"version":3,"sources":["../src/dayOfYear.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { MaybeDateInput } 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 or nothing for the current day.\n */\nexport function dayOfYear(inputDate?: MaybeDateInput): number {\n const d = date(inputDate)\n // Count calendar days independently of local offset changes or skipped dates.\n return (\n (Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()) -\n Date.UTC(d.getFullYear(), 0, 0)) /\n 86400000\n )\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAQd,SAAS,UAAU,WAAoC;AAC5D,QAAM,IAAI,KAAK,SAAS;AAExB,UACG,KAAK,IAAI,EAAE,YAAY,GAAG,EAAE,SAAS,GAAG,EAAE,QAAQ,CAAC,IAClD,KAAK,IAAI,EAAE,YAAY,GAAG,GAAG,CAAC,KAC9B;AAEN;","names":[]}
|
package/dist/diffDays.mjs
CHANGED
|
@@ -1,13 +1,11 @@
|
|
|
1
1
|
// src/diffDays.ts
|
|
2
|
-
import {
|
|
2
|
+
import { date } from "./date.mjs";
|
|
3
3
|
import { diffRound } from "./diffRound.mjs";
|
|
4
4
|
function diffDays(dateA, dateB, roundingMethod) {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
roundingMethod
|
|
10
|
-
);
|
|
5
|
+
const left = date(dateA);
|
|
6
|
+
const right = date(dateB);
|
|
7
|
+
const offset = (right.getTimezoneOffset() - left.getTimezoneOffset()) * 6e4;
|
|
8
|
+
return diffRound((+left - +right + offset) / 864e5, roundingMethod);
|
|
11
9
|
}
|
|
12
10
|
export {
|
|
13
11
|
diffDays
|
package/dist/diffDays.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/diffDays.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../src/diffDays.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { DateInput, MaybeDateInput } 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 or nothing to compare with the current time\n * @param [roundingMethod] - the rounding method to use, default: trunc\n */\nexport function diffDays(\n dateA: DateInput,\n dateB?: MaybeDateInput,\n roundingMethod?: DiffRoundingMethod\n): number\n/**\n * Returns the difference between 2 dates in days.\n * @param [dateA] - A date to compare with the right date or null to compare with the current time\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: MaybeDateInput,\n dateB: DateInput,\n roundingMethod?: DiffRoundingMethod\n): number\n\nexport function diffDays(\n dateA: MaybeDateInput,\n dateB?: MaybeDateInput,\n roundingMethod?: DiffRoundingMethod\n): number {\n const left = date(dateA)\n const right = date(dateB)\n // Count local days: a DST change makes one day 23 or 25 hours long.\n const offset = (right.getTimezoneOffset() - left.getTimezoneOffset()) * 60_000\n return diffRound((+left - +right + offset) / 86_400_000, roundingMethod) // hour * 24\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAErB,SAAS,iBAA0C;AAyB5C,SAAS,SACd,OACA,OACA,gBACQ;AACR,QAAM,OAAO,KAAK,KAAK;AACvB,QAAM,QAAQ,KAAK,KAAK;AAExB,QAAM,UAAU,MAAM,kBAAkB,IAAI,KAAK,kBAAkB,KAAK;AACxE,SAAO,WAAW,CAAC,OAAO,CAAC,QAAQ,UAAU,OAAY,cAAc;AACzE;","names":[]}
|
package/dist/diffMonths.mjs
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
// src/diffMonths.ts
|
|
2
2
|
import { date } from "./date.mjs";
|
|
3
3
|
import { monthDays } from "./monthDays.mjs";
|
|
4
|
+
function timeOfDay(d) {
|
|
5
|
+
return ((d.getHours() * 60 + d.getMinutes()) * 60 + d.getSeconds()) * 1e3 + d.getMilliseconds();
|
|
6
|
+
}
|
|
4
7
|
function diffMonths(dateA, dateB) {
|
|
5
8
|
const l = date(dateA);
|
|
6
9
|
const r = date(dateB);
|
|
@@ -11,7 +14,7 @@ function diffMonths(dateA, dateB) {
|
|
|
11
14
|
let months = (l.getFullYear() - r.getFullYear()) * 12 + (l.getMonth() - r.getMonth());
|
|
12
15
|
const ld = l.getDate();
|
|
13
16
|
const rd = r.getDate();
|
|
14
|
-
if (ld < rd) {
|
|
17
|
+
if (ld < rd || ld == rd && timeOfDay(l) < timeOfDay(r)) {
|
|
15
18
|
const lm = monthDays(l);
|
|
16
19
|
if (!(lm == ld && lm < rd)) {
|
|
17
20
|
months--;
|
package/dist/diffMonths.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/diffMonths.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { DateInput, MaybeDateInput } 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 or nothing to compare with the current time\n */\nexport function diffMonths(dateA: DateInput, dateB?: MaybeDateInput): number\n/**\n * Returns the difference between 2 dates in months.\n * @param [dateA] - A date to compare with the dateB date or null to compare with the current time\n * @param dateB - A date to compare with the dateA date\n */\nexport function diffMonths(dateA: MaybeDateInput, dateB: DateInput): number\n\nexport function diffMonths(dateA: MaybeDateInput, dateB?: MaybeDateInput): 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 = (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;
|
|
1
|
+
{"version":3,"sources":["../src/diffMonths.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { DateInput, MaybeDateInput } from \"./types\"\nimport { monthDays } from \"./monthDays\"\n\n/**\n * Milliseconds since local midnight.\n */\nfunction timeOfDay(d: Date): number {\n return (\n ((d.getHours() * 60 + d.getMinutes()) * 60 + d.getSeconds()) * 1000 +\n d.getMilliseconds()\n )\n}\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 or nothing to compare with the current time\n */\nexport function diffMonths(dateA: DateInput, dateB?: MaybeDateInput): number\n/**\n * Returns the difference between 2 dates in months.\n * @param [dateA] - A date to compare with the dateB date or null to compare with the current time\n * @param dateB - A date to compare with the dateA date\n */\nexport function diffMonths(dateA: MaybeDateInput, dateB: DateInput): number\n\nexport function diffMonths(dateA: MaybeDateInput, dateB?: MaybeDateInput): 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 = (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 || (ld == rd && timeOfDay(l) < timeOfDay(r))) {\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;AAK1B,SAAS,UAAU,GAAiB;AAClC,WACI,EAAE,SAAS,IAAI,KAAK,EAAE,WAAW,KAAK,KAAK,EAAE,WAAW,KAAK,MAC/D,EAAE,gBAAgB;AAEtB;AAeO,SAAS,WAAW,OAAuB,OAAgC;AAChF,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,UAAU,EAAE,YAAY,IAAI,EAAE,YAAY,KAAK,MAAM,EAAE,SAAS,IAAI,EAAE,SAAS;AAEnF,QAAM,KAAK,EAAE,QAAQ;AACrB,QAAM,KAAK,EAAE,QAAQ;AAGrB,MAAI,KAAK,MAAO,MAAM,MAAM,UAAU,CAAC,IAAI,UAAU,CAAC,GAAI;AAExD,UAAM,KAAK,UAAU,CAAC;AACtB,QAAI,EAAE,MAAM,MAAM,KAAK,KAAK;AAC1B;AAAA,IACF;AAAA,EACF;AAEA,SAAO,UAAU,IAAI,IAAI;AAC3B;","names":[]}
|
package/dist/diffWeeks.d.ts
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
import { DateInput } from './types.js';
|
|
1
|
+
import { DateInput, MaybeDateInput } from './types.js';
|
|
2
2
|
import { DiffRoundingMethod } from './diffRound.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
|
-
* Returns the difference between 2 dates in
|
|
5
|
+
* Returns the difference between 2 dates in weeks.
|
|
6
6
|
* @param dateA - A date to compare with the right date
|
|
7
7
|
* @param [dateB] - A date to compare with the left date or nothing to compare with the current time
|
|
8
8
|
* @param [roundingMethod] - the rounding method to use, default: trunc
|
|
9
9
|
*/
|
|
10
|
-
declare function diffWeeks(dateA: DateInput, dateB
|
|
10
|
+
declare function diffWeeks(dateA: DateInput, dateB?: MaybeDateInput, roundingMethod?: DiffRoundingMethod): number;
|
|
11
11
|
/**
|
|
12
|
-
* Returns the difference between 2 dates in
|
|
12
|
+
* Returns the difference between 2 dates in weeks.
|
|
13
13
|
* @param [dateA] - A date to compare with the right date or null to compare with the current time
|
|
14
14
|
* @param dateB - A date to compare with the left date
|
|
15
15
|
* @param [roundingMethod] - the rounding method to use, default: trunc
|
|
16
16
|
*/
|
|
17
|
-
declare function diffWeeks(dateA:
|
|
17
|
+
declare function diffWeeks(dateA: MaybeDateInput, dateB: DateInput, roundingMethod?: DiffRoundingMethod): number;
|
|
18
18
|
|
|
19
19
|
export { diffWeeks };
|
package/dist/diffWeeks.mjs
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
// src/diffWeeks.ts
|
|
2
|
-
import {
|
|
2
|
+
import { date } from "./date.mjs";
|
|
3
3
|
import { diffRound } from "./diffRound.mjs";
|
|
4
4
|
function diffWeeks(dateA, dateB, roundingMethod) {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
);
|
|
5
|
+
const left = date(dateA);
|
|
6
|
+
const right = date(dateB);
|
|
7
|
+
const offset = (right.getTimezoneOffset() - left.getTimezoneOffset()) * 6e4;
|
|
8
|
+
return diffRound((+left - +right + offset) / 6048e5, roundingMethod);
|
|
10
9
|
}
|
|
11
10
|
export {
|
|
12
11
|
diffWeeks
|
package/dist/diffWeeks.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/diffWeeks.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../src/diffWeeks.ts"],"sourcesContent":["import { date } from \"./date\"\nimport { DateInput, MaybeDateInput } from \"./types\"\nimport { diffRound, type DiffRoundingMethod } from \"./diffRound\"\n\n/**\n * Returns the difference between 2 dates in weeks.\n * @param dateA - A date to compare with the right date\n * @param [dateB] - A date to compare with the left date or nothing to compare with the current time\n * @param [roundingMethod] - the rounding method to use, default: trunc\n */\nexport function diffWeeks(\n dateA: DateInput,\n dateB?: MaybeDateInput,\n roundingMethod?: DiffRoundingMethod\n): number\n\n/**\n * Returns the difference between 2 dates in weeks.\n * @param [dateA] - A date to compare with the right date or null to compare with the current time\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: MaybeDateInput,\n dateB: DateInput,\n roundingMethod?: DiffRoundingMethod\n): number\n\nexport function diffWeeks(\n dateA: MaybeDateInput,\n dateB?: MaybeDateInput,\n roundingMethod?: DiffRoundingMethod\n): number {\n const left = date(dateA)\n const right = date(dateB)\n // Count local days: a DST change makes one day 23 or 25 hours long.\n const offset = (right.getTimezoneOffset() - left.getTimezoneOffset()) * 60_000\n return diffRound((+left - +right + offset) / 604800000, roundingMethod) // day * 7\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAErB,SAAS,iBAA0C;AA0B5C,SAAS,UACd,OACA,OACA,gBACQ;AACR,QAAM,OAAO,KAAK,KAAK;AACvB,QAAM,QAAQ,KAAK,KAAK;AAExB,QAAM,UAAU,MAAM,kBAAkB,IAAI,KAAK,kBAAkB,KAAK;AACxE,SAAO,WAAW,CAAC,OAAO,CAAC,QAAQ,UAAU,QAAW,cAAc;AACxE;","names":[]}
|
package/dist/hourEnd.mjs
CHANGED
|
@@ -2,6 +2,11 @@
|
|
|
2
2
|
import { date } from "./date.mjs";
|
|
3
3
|
function hourEnd(inputDate) {
|
|
4
4
|
const d = date(inputDate);
|
|
5
|
+
const shifted = new Date(
|
|
6
|
+
d.getTime() + ((59 - d.getMinutes()) * 60 + (59 - d.getSeconds())) * 1e3 + (999 - d.getMilliseconds())
|
|
7
|
+
);
|
|
8
|
+
if (shifted.getMinutes() === 59 && shifted.getHours() === d.getHours())
|
|
9
|
+
return shifted;
|
|
5
10
|
d.setMinutes(59, 59, 999);
|
|
6
11
|
return d;
|
|
7
12
|
}
|
package/dist/hourEnd.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/hourEnd.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { MaybeDateInput } from \"./types\"\n\n/**\n * Returns a Date object for end of the given hour.\n * @param [inputDate] - A string, Date object or nothing for the current time\n */\nexport function hourEnd(inputDate?: MaybeDateInput): Date {\n const d = date(inputDate)\n d.setMinutes(59, 59, 999)\n return d\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAOd,SAAS,QAAQ,WAAkC;AACxD,QAAM,IAAI,KAAK,SAAS;
|
|
1
|
+
{"version":3,"sources":["../src/hourEnd.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { MaybeDateInput } from \"./types\"\n\n/**\n * Returns a Date object for end of the given hour.\n * @param [inputDate] - A string, Date object or nothing for the current time\n */\nexport function hourEnd(inputDate?: MaybeDateInput): Date {\n const d = date(inputDate)\n // Shift the timestamp instead of using local setters, which pick the first\n // occurrence of a repeated hour (DST fall-back).\n const shifted = new Date(\n d.getTime() +\n ((59 - d.getMinutes()) * 60 + (59 - d.getSeconds())) * 1000 +\n (999 - d.getMilliseconds())\n )\n // A sub-hour offset change (e.g. 30 min in Lord_Howe) breaks the shift.\n if (shifted.getMinutes() === 59 && shifted.getHours() === d.getHours())\n return shifted\n d.setMinutes(59, 59, 999)\n return d\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAOd,SAAS,QAAQ,WAAkC;AACxD,QAAM,IAAI,KAAK,SAAS;AAGxB,QAAM,UAAU,IAAI;AAAA,IAClB,EAAE,QAAQ,MACN,KAAK,EAAE,WAAW,KAAK,MAAM,KAAK,EAAE,WAAW,MAAM,OACtD,MAAM,EAAE,gBAAgB;AAAA,EAC7B;AAEA,MAAI,QAAQ,WAAW,MAAM,MAAM,QAAQ,SAAS,MAAM,EAAE,SAAS;AACnE,WAAO;AACT,IAAE,WAAW,IAAI,IAAI,GAAG;AACxB,SAAO;AACT;","names":[]}
|
package/dist/hourStart.mjs
CHANGED
|
@@ -2,6 +2,10 @@
|
|
|
2
2
|
import { date } from "./date.mjs";
|
|
3
3
|
function hourStart(inputDate) {
|
|
4
4
|
const d = date(inputDate);
|
|
5
|
+
const shifted = new Date(
|
|
6
|
+
d.getTime() - (d.getMinutes() * 60 + d.getSeconds()) * 1e3 - d.getMilliseconds()
|
|
7
|
+
);
|
|
8
|
+
if (shifted.getMinutes() === 0 && shifted.getHours() === d.getHours()) return shifted;
|
|
5
9
|
d.setMinutes(0, 0, 0);
|
|
6
10
|
return d;
|
|
7
11
|
}
|
package/dist/hourStart.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/hourStart.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { MaybeDateInput } from \"./types\"\n\n/**\n * Returns a Date object for start of the given hour.\n * @param [inputDate] - A string, Date object or nothing for the current time\n */\nexport function hourStart(inputDate?: MaybeDateInput): Date {\n const d = date(inputDate)\n d.setMinutes(0, 0, 0)\n return d\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAOd,SAAS,UAAU,WAAkC;AAC1D,QAAM,IAAI,KAAK,SAAS;
|
|
1
|
+
{"version":3,"sources":["../src/hourStart.ts"],"sourcesContent":["import { date } from \"./date\"\nimport type { MaybeDateInput } from \"./types\"\n\n/**\n * Returns a Date object for start of the given hour.\n * @param [inputDate] - A string, Date object or nothing for the current time\n */\nexport function hourStart(inputDate?: MaybeDateInput): Date {\n const d = date(inputDate)\n // Shift the timestamp instead of using local setters, which pick the first\n // occurrence of a repeated hour (DST fall-back).\n const shifted = new Date(\n d.getTime() -\n (d.getMinutes() * 60 + d.getSeconds()) * 1000 -\n d.getMilliseconds()\n )\n // A sub-hour offset change (e.g. 30 min in Lord_Howe) breaks the shift.\n if (shifted.getMinutes() === 0 && shifted.getHours() === d.getHours()) return shifted\n d.setMinutes(0, 0, 0)\n return d\n}\n"],"mappings":";AAAA,SAAS,YAAY;AAOd,SAAS,UAAU,WAAkC;AAC1D,QAAM,IAAI,KAAK,SAAS;AAGxB,QAAM,UAAU,IAAI;AAAA,IAClB,EAAE,QAAQ,KACP,EAAE,WAAW,IAAI,KAAK,EAAE,WAAW,KAAK,MACzC,EAAE,gBAAgB;AAAA,EACtB;AAEA,MAAI,QAAQ,WAAW,MAAM,KAAK,QAAQ,SAAS,MAAM,EAAE,SAAS,EAAG,QAAO;AAC9E,IAAE,WAAW,GAAG,GAAG,CAAC;AACpB,SAAO;AACT;","names":[]}
|
package/dist/index.cjs
CHANGED
|
@@ -474,8 +474,9 @@ function isNumeric(part) {
|
|
|
474
474
|
}
|
|
475
475
|
function validate(parts2) {
|
|
476
476
|
let lastPart = void 0;
|
|
477
|
-
|
|
478
|
-
|
|
477
|
+
const knownWidth = (p) => !p || p.partName === "literal" || p.token in fixedLength;
|
|
478
|
+
for (const [i, part] of parts2.entries()) {
|
|
479
|
+
if (part.partName === "literal" && !isNaN(parseFloat(part.partValue)) && !(knownWidth(parts2[i - 1]) && knownWidth(parts2[i + 1]))) {
|
|
479
480
|
throw new Error(`Numbers in format (${part.partValue}).`);
|
|
480
481
|
}
|
|
481
482
|
if (lastPart && lastPart.partName !== "literal" && part.partName !== "literal") {
|
|
@@ -572,9 +573,7 @@ function tzDate(inputDate, tz) {
|
|
|
572
573
|
// src/dayOfYear.ts
|
|
573
574
|
function dayOfYear(inputDate) {
|
|
574
575
|
const d = date(inputDate);
|
|
575
|
-
return
|
|
576
|
-
(new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0, 0).getTime() - new Date(d.getFullYear(), 0, 0).getTime()) / 864e5
|
|
577
|
-
);
|
|
576
|
+
return (Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()) - Date.UTC(d.getFullYear(), 0, 0)) / 864e5;
|
|
578
577
|
}
|
|
579
578
|
|
|
580
579
|
// src/dayEnd.ts
|
|
@@ -852,6 +851,11 @@ function fourDigitYear(value) {
|
|
|
852
851
|
// src/hourEnd.ts
|
|
853
852
|
function hourEnd(inputDate) {
|
|
854
853
|
const d = date(inputDate);
|
|
854
|
+
const shifted = new Date(
|
|
855
|
+
d.getTime() + ((59 - d.getMinutes()) * 60 + (59 - d.getSeconds())) * 1e3 + (999 - d.getMilliseconds())
|
|
856
|
+
);
|
|
857
|
+
if (shifted.getMinutes() === 59 && shifted.getHours() === d.getHours())
|
|
858
|
+
return shifted;
|
|
855
859
|
d.setMinutes(59, 59, 999);
|
|
856
860
|
return d;
|
|
857
861
|
}
|
|
@@ -859,6 +863,10 @@ function hourEnd(inputDate) {
|
|
|
859
863
|
// src/hourStart.ts
|
|
860
864
|
function hourStart(inputDate) {
|
|
861
865
|
const d = date(inputDate);
|
|
866
|
+
const shifted = new Date(
|
|
867
|
+
d.getTime() - (d.getMinutes() * 60 + d.getSeconds()) * 1e3 - d.getMilliseconds()
|
|
868
|
+
);
|
|
869
|
+
if (shifted.getMinutes() === 0 && shifted.getHours() === d.getHours()) return shifted;
|
|
862
870
|
d.setMinutes(0, 0, 0);
|
|
863
871
|
return d;
|
|
864
872
|
}
|
|
@@ -866,14 +874,16 @@ function hourStart(inputDate) {
|
|
|
866
874
|
// src/minuteEnd.ts
|
|
867
875
|
function minuteEnd(inputDate) {
|
|
868
876
|
const d = date(inputDate);
|
|
869
|
-
d.
|
|
877
|
+
d.setTime(
|
|
878
|
+
d.getTime() + (59 - d.getSeconds()) * 1e3 + (999 - d.getMilliseconds())
|
|
879
|
+
);
|
|
870
880
|
return d;
|
|
871
881
|
}
|
|
872
882
|
|
|
873
883
|
// src/minuteStart.ts
|
|
874
884
|
function minuteStart(inputDate) {
|
|
875
885
|
const d = date(inputDate);
|
|
876
|
-
d.
|
|
886
|
+
d.setTime(d.getTime() - d.getSeconds() * 1e3 - d.getMilliseconds());
|
|
877
887
|
return d;
|
|
878
888
|
}
|
|
879
889
|
|
|
@@ -898,23 +908,23 @@ function nearestDay(inputDate, search, constraint = 7) {
|
|
|
898
908
|
const d = date(inputDate);
|
|
899
909
|
switch (constraint) {
|
|
900
910
|
case "month":
|
|
901
|
-
decrements = d.getDate();
|
|
911
|
+
decrements = d.getDate() - 1;
|
|
902
912
|
increments = monthDays(d) - d.getDate();
|
|
903
913
|
break;
|
|
904
914
|
case "week":
|
|
905
|
-
decrements = d.getDay()
|
|
915
|
+
decrements = d.getDay();
|
|
906
916
|
increments = 6 - d.getDay();
|
|
907
917
|
break;
|
|
908
918
|
case "year":
|
|
909
919
|
const total = yearDays(d);
|
|
910
920
|
const day = dayOfYear(d);
|
|
911
|
-
decrements = day;
|
|
921
|
+
decrements = day - 1;
|
|
912
922
|
increments = total - day;
|
|
913
923
|
break;
|
|
914
924
|
default:
|
|
915
925
|
increments = decrements = constraint;
|
|
916
926
|
}
|
|
917
|
-
for (let i = 0; i <= increments || i
|
|
927
|
+
for (let i = 0; i <= increments || i <= decrements; i++) {
|
|
918
928
|
if (i <= increments) {
|
|
919
929
|
const next = addDay(d, i);
|
|
920
930
|
if (search(next)) return next;
|
|
@@ -1355,24 +1365,24 @@ function diffHours(dateA, dateB, roundingMethod) {
|
|
|
1355
1365
|
|
|
1356
1366
|
// src/diffDays.ts
|
|
1357
1367
|
function diffDays(dateA, dateB, roundingMethod) {
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
roundingMethod
|
|
1363
|
-
);
|
|
1368
|
+
const left = date(dateA);
|
|
1369
|
+
const right = date(dateB);
|
|
1370
|
+
const offset2 = (right.getTimezoneOffset() - left.getTimezoneOffset()) * 6e4;
|
|
1371
|
+
return diffRound((+left - +right + offset2) / 864e5, roundingMethod);
|
|
1364
1372
|
}
|
|
1365
1373
|
|
|
1366
1374
|
// src/diffWeeks.ts
|
|
1367
1375
|
function diffWeeks(dateA, dateB, roundingMethod) {
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
);
|
|
1376
|
+
const left = date(dateA);
|
|
1377
|
+
const right = date(dateB);
|
|
1378
|
+
const offset2 = (right.getTimezoneOffset() - left.getTimezoneOffset()) * 6e4;
|
|
1379
|
+
return diffRound((+left - +right + offset2) / 6048e5, roundingMethod);
|
|
1373
1380
|
}
|
|
1374
1381
|
|
|
1375
1382
|
// src/diffMonths.ts
|
|
1383
|
+
function timeOfDay(d) {
|
|
1384
|
+
return ((d.getHours() * 60 + d.getMinutes()) * 60 + d.getSeconds()) * 1e3 + d.getMilliseconds();
|
|
1385
|
+
}
|
|
1376
1386
|
function diffMonths(dateA, dateB) {
|
|
1377
1387
|
const l = date(dateA);
|
|
1378
1388
|
const r = date(dateB);
|
|
@@ -1383,7 +1393,7 @@ function diffMonths(dateA, dateB) {
|
|
|
1383
1393
|
let months = (l.getFullYear() - r.getFullYear()) * 12 + (l.getMonth() - r.getMonth());
|
|
1384
1394
|
const ld = l.getDate();
|
|
1385
1395
|
const rd = r.getDate();
|
|
1386
|
-
if (ld < rd) {
|
|
1396
|
+
if (ld < rd || ld == rd && timeOfDay(l) < timeOfDay(r)) {
|
|
1387
1397
|
const lm = monthDays(l);
|
|
1388
1398
|
if (!(lm == ld && lm < rd)) {
|
|
1389
1399
|
months--;
|