@facilis.dev/time 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +18 -2
- package/dist/calendar.d.ts +8 -0
- package/dist/calendar.js +24 -0
- package/dist/date-only.d.ts +41 -0
- package/dist/date-only.js +79 -0
- package/dist/day-bounds.d.ts +11 -0
- package/dist/day-bounds.js +41 -0
- package/dist/describe-value.d.ts +7 -0
- package/dist/describe-value.js +13 -0
- package/dist/format.d.ts +26 -0
- package/dist/format.js +69 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +11 -0
- package/dist/instant.d.ts +11 -0
- package/dist/instant.js +60 -0
- package/dist/zone.d.ts +28 -0
- package/dist/zone.js +96 -0
- package/package.json +39 -4
- package/src/calendar.ts +28 -0
- package/src/date-only.ts +106 -0
- package/src/day-bounds.ts +53 -0
- package/src/describe-value.ts +11 -0
- package/src/format.ts +109 -0
- package/src/index.ts +15 -0
- package/src/instant.ts +72 -0
- package/src/zone.ts +126 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 facilis-dev
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,19 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @facilis.dev/time
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Facilis date/time logic: zero-dependency, Intl-based formatting and calendar-day handling with explicit time zones.
|
|
4
|
+
|
|
5
|
+
Part of [Facilis](https://github.com/facilis-dev/facilis), a browser-first low-code framework: the Studio
|
|
6
|
+
runs a generated project in a WebContainer where vite dev is the only dev server
|
|
7
|
+
and Nitro v3 runs as a Vite plugin. Framework contracts live in
|
|
8
|
+
[docs/SPEC.md](https://github.com/facilis-dev/facilis/blob/main/docs/SPEC.md) and architectural decisions in
|
|
9
|
+
[docs/DECISIONS.md](https://github.com/facilis-dev/facilis/blob/main/docs/DECISIONS.md).
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
npm install @facilis.dev/time
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
The package publishes its TypeScript sources and its compiled dist/; the exports map
|
|
16
|
+
of the published manifest points at dist/, so Node and bundlers load JavaScript and
|
|
17
|
+
the bundled .d.ts files.
|
|
18
|
+
|
|
19
|
+
Licensed under the MIT License.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The calendar day of an instant, read in an explicit zone.
|
|
3
|
+
*/
|
|
4
|
+
import { type DateInput } from "./instant.js";
|
|
5
|
+
/** The YYYY-MM-DD the instant falls on in the zone (defaults to the runtime zone). */
|
|
6
|
+
export declare function dateOnlyOf(value: DateInput, timeZone?: string): string;
|
|
7
|
+
/** dateOnlyOf(now, timeZone) - "today" always means "today in that zone". */
|
|
8
|
+
export declare function today(timeZone?: string, now?: DateInput): string;
|
package/dist/calendar.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The calendar day of an instant, read in an explicit zone.
|
|
3
|
+
*/
|
|
4
|
+
import { serializeDateOnly } from "./date-only.js";
|
|
5
|
+
import { toInstant } from "./instant.js";
|
|
6
|
+
import { wallPartsAt } from "./zone.js";
|
|
7
|
+
/** The YYYY-MM-DD the instant falls on in the zone (defaults to the runtime zone). */
|
|
8
|
+
export function dateOnlyOf(value, timeZone) {
|
|
9
|
+
const instant = toInstant(value);
|
|
10
|
+
const parts = wallPartsAt(instant.getTime(), timeZone);
|
|
11
|
+
assertCalendarDayRange(parts);
|
|
12
|
+
return serializeDateOnly(parts);
|
|
13
|
+
}
|
|
14
|
+
/** dateOnlyOf(now, timeZone) - "today" always means "today in that zone". */
|
|
15
|
+
export function today(timeZone, now = new Date()) {
|
|
16
|
+
return dateOnlyOf(now, timeZone);
|
|
17
|
+
}
|
|
18
|
+
function assertCalendarDayRange(parts) {
|
|
19
|
+
// The pinned gregory formatter reports BCE years as positive numbers with a "BC" era; neither
|
|
20
|
+
// those nor years above 9999 can be written as a YYYY-MM-DD calendar day.
|
|
21
|
+
if (parts.era === "BC" || parts.year < 1 || parts.year > 9999) {
|
|
22
|
+
throw new RangeError("@facilis.dev/time: the instant is outside the supported calendar-day range");
|
|
23
|
+
}
|
|
24
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Calendar-day ("YYYY-MM-DD") values.
|
|
3
|
+
*
|
|
4
|
+
* A calendar day is a plain string in this package: it names no instant and no zone, so it must
|
|
5
|
+
* never be routed through a Date in the runtime zone (that is exactly how date pickers shift a
|
|
6
|
+
* day). All arithmetic here is on the proleptic Gregorian calendar, years 0001-9999.
|
|
7
|
+
*/
|
|
8
|
+
export interface DateOnlyParts {
|
|
9
|
+
year: number;
|
|
10
|
+
month: number;
|
|
11
|
+
day: number;
|
|
12
|
+
}
|
|
13
|
+
/** Wall-clock fields of a local time; fields below the hour are optional. */
|
|
14
|
+
export interface DateTimeParts extends DateOnlyParts {
|
|
15
|
+
hour?: number;
|
|
16
|
+
minute?: number;
|
|
17
|
+
second?: number;
|
|
18
|
+
millisecond?: number;
|
|
19
|
+
}
|
|
20
|
+
/** Whether the fields name a date in the proleptic Gregorian calendar (no year range check). */
|
|
21
|
+
export declare function isRealCalendarDate(year: number, month: number, day: number): boolean;
|
|
22
|
+
/**
|
|
23
|
+
* Parses a YYYY-MM-DD calendar day, throwing for everything else.
|
|
24
|
+
*
|
|
25
|
+
* This is the single source of truth for the format: isValidDateOnly is this parser inside a
|
|
26
|
+
* try/catch, so the validator and the consumers cannot drift apart.
|
|
27
|
+
*/
|
|
28
|
+
export declare function parseDateOnly(value: unknown): DateOnlyParts;
|
|
29
|
+
/** Strict guard for the calendar-day contract; non-strings are not dates rather than errors. */
|
|
30
|
+
export declare function isValidDateOnly(value: unknown): value is string;
|
|
31
|
+
/** Serializes calendar fields as YYYY-MM-DD; callers pass an already valid date. */
|
|
32
|
+
export declare function serializeDateOnly(parts: DateOnlyParts): string;
|
|
33
|
+
/**
|
|
34
|
+
* UTC instant of the given wall-clock fields.
|
|
35
|
+
*
|
|
36
|
+
* Date.UTC maps years 0-99 to 1900-1999, so the fields are applied with setUTCFullYear instead;
|
|
37
|
+
* that is what keeps 0001-01-01 and 9999-12-31 correct.
|
|
38
|
+
*/
|
|
39
|
+
export declare function utcDateFromParts(parts: DateTimeParts): Date;
|
|
40
|
+
/** Calendar-day arithmetic, with month and year roll-over. */
|
|
41
|
+
export declare function addDays(parts: DateOnlyParts, days: number): DateOnlyParts;
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Calendar-day ("YYYY-MM-DD") values.
|
|
3
|
+
*
|
|
4
|
+
* A calendar day is a plain string in this package: it names no instant and no zone, so it must
|
|
5
|
+
* never be routed through a Date in the runtime zone (that is exactly how date pickers shift a
|
|
6
|
+
* day). All arithmetic here is on the proleptic Gregorian calendar, years 0001-9999.
|
|
7
|
+
*/
|
|
8
|
+
import { describeValue } from "./describe-value.js";
|
|
9
|
+
const DATE_ONLY_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
10
|
+
/** Days per month in a non-leap year; February is handled by isRealCalendarDate. */
|
|
11
|
+
const DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
|
12
|
+
function isLeapYear(year) {
|
|
13
|
+
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
|
|
14
|
+
}
|
|
15
|
+
/** Whether the fields name a date in the proleptic Gregorian calendar (no year range check). */
|
|
16
|
+
export function isRealCalendarDate(year, month, day) {
|
|
17
|
+
if (month < 1 || month > 12 || day < 1)
|
|
18
|
+
return false;
|
|
19
|
+
const longestDay = month === 2 && isLeapYear(year) ? 29 : (DAYS_IN_MONTH[month - 1] ?? 0);
|
|
20
|
+
return day <= longestDay;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Parses a YYYY-MM-DD calendar day, throwing for everything else.
|
|
24
|
+
*
|
|
25
|
+
* This is the single source of truth for the format: isValidDateOnly is this parser inside a
|
|
26
|
+
* try/catch, so the validator and the consumers cannot drift apart.
|
|
27
|
+
*/
|
|
28
|
+
export function parseDateOnly(value) {
|
|
29
|
+
if (typeof value !== "string") {
|
|
30
|
+
throw new TypeError("@facilis.dev/time: expected a YYYY-MM-DD string, received " + describeValue(value));
|
|
31
|
+
}
|
|
32
|
+
const match = DATE_ONLY_PATTERN.exec(value);
|
|
33
|
+
if (match === null) {
|
|
34
|
+
throw new RangeError('@facilis.dev/time: "' + value + '" is not a YYYY-MM-DD calendar date');
|
|
35
|
+
}
|
|
36
|
+
const year = Number(match[1]);
|
|
37
|
+
const month = Number(match[2]);
|
|
38
|
+
const day = Number(match[3]);
|
|
39
|
+
if (year < 1 || year > 9999 || !isRealCalendarDate(year, month, day)) {
|
|
40
|
+
throw new RangeError('@facilis.dev/time: "' +
|
|
41
|
+
value +
|
|
42
|
+
'" is not a real calendar date between 0001-01-01 and 9999-12-31');
|
|
43
|
+
}
|
|
44
|
+
return { year, month, day };
|
|
45
|
+
}
|
|
46
|
+
/** Strict guard for the calendar-day contract; non-strings are not dates rather than errors. */
|
|
47
|
+
export function isValidDateOnly(value) {
|
|
48
|
+
try {
|
|
49
|
+
parseDateOnly(value);
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/** Serializes calendar fields as YYYY-MM-DD; callers pass an already valid date. */
|
|
57
|
+
export function serializeDateOnly(parts) {
|
|
58
|
+
return pad(parts.year, 4) + "-" + pad(parts.month, 2) + "-" + pad(parts.day, 2);
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* UTC instant of the given wall-clock fields.
|
|
62
|
+
*
|
|
63
|
+
* Date.UTC maps years 0-99 to 1900-1999, so the fields are applied with setUTCFullYear instead;
|
|
64
|
+
* that is what keeps 0001-01-01 and 9999-12-31 correct.
|
|
65
|
+
*/
|
|
66
|
+
export function utcDateFromParts(parts) {
|
|
67
|
+
const date = new Date(0);
|
|
68
|
+
date.setUTCFullYear(parts.year, parts.month - 1, parts.day);
|
|
69
|
+
date.setUTCHours(parts.hour ?? 0, parts.minute ?? 0, parts.second ?? 0, parts.millisecond ?? 0);
|
|
70
|
+
return date;
|
|
71
|
+
}
|
|
72
|
+
/** Calendar-day arithmetic, with month and year roll-over. */
|
|
73
|
+
export function addDays(parts, days) {
|
|
74
|
+
const date = utcDateFromParts({ ...parts, day: parts.day + days });
|
|
75
|
+
return { year: date.getUTCFullYear(), month: date.getUTCMonth() + 1, day: date.getUTCDate() };
|
|
76
|
+
}
|
|
77
|
+
function pad(value, length) {
|
|
78
|
+
return String(value).padStart(length, "0");
|
|
79
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The UTC instants at which a local calendar day starts and ends.
|
|
3
|
+
*
|
|
4
|
+
* Boundaries are anchored on local midnight and computed by probing the zone offset instead of
|
|
5
|
+
* adding to a naive local time: a DST day can be 23 or 25 hours long, so only the wall clock
|
|
6
|
+
* and the zone offset tell the truth.
|
|
7
|
+
*/
|
|
8
|
+
/** UTC instant of local 00:00 on the calendar day in the zone (DST-aware). */
|
|
9
|
+
export declare function startOfDay(dateOnly: string, timeZone: string): Date;
|
|
10
|
+
/** UTC instant of local 23:59:59.999 on the calendar day in the zone (DST-aware). */
|
|
11
|
+
export declare function endOfDay(dateOnly: string, timeZone: string): Date;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The UTC instants at which a local calendar day starts and ends.
|
|
3
|
+
*
|
|
4
|
+
* Boundaries are anchored on local midnight and computed by probing the zone offset instead of
|
|
5
|
+
* adding to a naive local time: a DST day can be 23 or 25 hours long, so only the wall clock
|
|
6
|
+
* and the zone offset tell the truth.
|
|
7
|
+
*/
|
|
8
|
+
import { addDays, parseDateOnly, utcDateFromParts } from "./date-only.js";
|
|
9
|
+
import { assertTimeZone, isSameWallTime, wallPartsAt, zoneOffsetMs, } from "./zone.js";
|
|
10
|
+
/** UTC instant of local 00:00 on the calendar day in the zone (DST-aware). */
|
|
11
|
+
export function startOfDay(dateOnly, timeZone) {
|
|
12
|
+
assertTimeZone(timeZone);
|
|
13
|
+
return new Date(startOfDayMs(parseDateOnly(dateOnly), timeZone));
|
|
14
|
+
}
|
|
15
|
+
/** UTC instant of local 23:59:59.999 on the calendar day in the zone (DST-aware). */
|
|
16
|
+
export function endOfDay(dateOnly, timeZone) {
|
|
17
|
+
assertTimeZone(timeZone);
|
|
18
|
+
// The first millisecond of the next local day is a day's exclusive end in every zone, and
|
|
19
|
+
// subtracting one also handles a day whose final local second the zone skips.
|
|
20
|
+
return new Date(startOfDayMs(addDays(parseDateOnly(dateOnly), 1), timeZone) - 1);
|
|
21
|
+
}
|
|
22
|
+
function startOfDayMs(dateOnly, timeZone) {
|
|
23
|
+
const midnight = {
|
|
24
|
+
year: dateOnly.year,
|
|
25
|
+
month: dateOnly.month,
|
|
26
|
+
day: dateOnly.day,
|
|
27
|
+
hour: 0,
|
|
28
|
+
minute: 0,
|
|
29
|
+
second: 0,
|
|
30
|
+
};
|
|
31
|
+
// The instant of a wall-clock time is not a function of that time alone: a DST transition can
|
|
32
|
+
// repeat it or skip it, so the offset is probed on both sides of the naive instant.
|
|
33
|
+
const naive = utcDateFromParts(midnight).getTime();
|
|
34
|
+
const firstProbe = naive - zoneOffsetMs(naive, timeZone);
|
|
35
|
+
const secondProbe = naive - zoneOffsetMs(firstProbe, timeZone);
|
|
36
|
+
const candidates = [firstProbe, secondProbe].filter((candidate) => isSameWallTime(wallPartsAt(candidate, timeZone), midnight));
|
|
37
|
+
// Repeated local midnight (fall back): pick the earliest occurrence, so startOfDay - 1 ms is
|
|
38
|
+
// still the previous day. Skipped local midnight (spring forward): the day starts at the
|
|
39
|
+
// transition, which is the later probe.
|
|
40
|
+
return candidates.length > 0 ? Math.min(...candidates) : Math.max(firstProbe, secondProbe);
|
|
41
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Renders an unexpected value for an error message.
|
|
3
|
+
*
|
|
4
|
+
* typeof alone says "object" for null and arrays, which is exactly the confusion the TypeError
|
|
5
|
+
* messages exist to clear up.
|
|
6
|
+
*/
|
|
7
|
+
export function describeValue(value) {
|
|
8
|
+
if (value === null)
|
|
9
|
+
return "null";
|
|
10
|
+
if (Array.isArray(value))
|
|
11
|
+
return "an array";
|
|
12
|
+
return typeof value;
|
|
13
|
+
}
|
package/dist/format.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Localized formatting with an explicit locale and time zone.
|
|
3
|
+
*
|
|
4
|
+
* The style is fixed per function (medium date, short time) so a project gets one stable look
|
|
5
|
+
* without a prop surface; anything richer is "copy the function and pick the style".
|
|
6
|
+
*/
|
|
7
|
+
import { type DateInput } from "./instant.js";
|
|
8
|
+
/** Locale and zone for the instant formatters; both default to the runtime values. */
|
|
9
|
+
export interface FormatOptions {
|
|
10
|
+
/** BCP 47 locale tag. */
|
|
11
|
+
locale?: string;
|
|
12
|
+
/** IANA time zone name. */
|
|
13
|
+
timeZone?: string;
|
|
14
|
+
}
|
|
15
|
+
/** Calendar days have no zone, so only the locale applies. */
|
|
16
|
+
export interface DateOnlyFormatOptions {
|
|
17
|
+
locale?: string;
|
|
18
|
+
}
|
|
19
|
+
/** Localized date (medium style) in the requested zone. */
|
|
20
|
+
export declare function formatDate(value: DateInput, options?: FormatOptions): string;
|
|
21
|
+
/** Localized date and time in the requested zone. */
|
|
22
|
+
export declare function formatDateTime(value: DateInput, options?: FormatOptions): string;
|
|
23
|
+
/** Localized time in the requested zone. */
|
|
24
|
+
export declare function formatTime(value: DateInput, options?: FormatOptions): string;
|
|
25
|
+
/** Localized calendar date; it is anchored to UTC so the day never shifts. */
|
|
26
|
+
export declare function formatDateOnly(value: string, options?: DateOnlyFormatOptions): string;
|
package/dist/format.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Localized formatting with an explicit locale and time zone.
|
|
3
|
+
*
|
|
4
|
+
* The style is fixed per function (medium date, short time) so a project gets one stable look
|
|
5
|
+
* without a prop surface; anything richer is "copy the function and pick the style".
|
|
6
|
+
*/
|
|
7
|
+
import { describeValue } from "./describe-value.js";
|
|
8
|
+
import { parseDateOnly, utcDateFromParts } from "./date-only.js";
|
|
9
|
+
import { toInstant } from "./instant.js";
|
|
10
|
+
const STYLES = {
|
|
11
|
+
date: { dateStyle: "medium" },
|
|
12
|
+
"date-time": { dateStyle: "medium", timeStyle: "short" },
|
|
13
|
+
time: { timeStyle: "short" },
|
|
14
|
+
"calendar-date": { dateStyle: "medium" },
|
|
15
|
+
};
|
|
16
|
+
// Formatter construction dominates Intl formatting cost and an app uses a couple of
|
|
17
|
+
// locale/zone pairs; the cap keeps caller-supplied values from growing the cache without bound.
|
|
18
|
+
const MAX_CACHED_FORMATTERS = 64;
|
|
19
|
+
const FORMATTERS = new Map();
|
|
20
|
+
/** Localized date (medium style) in the requested zone. */
|
|
21
|
+
export function formatDate(value, options = {}) {
|
|
22
|
+
const { locale, timeZone } = readOptions(options);
|
|
23
|
+
return formatterFor("date", locale, timeZone).format(toInstant(value));
|
|
24
|
+
}
|
|
25
|
+
/** Localized date and time in the requested zone. */
|
|
26
|
+
export function formatDateTime(value, options = {}) {
|
|
27
|
+
const { locale, timeZone } = readOptions(options);
|
|
28
|
+
return formatterFor("date-time", locale, timeZone).format(toInstant(value));
|
|
29
|
+
}
|
|
30
|
+
/** Localized time in the requested zone. */
|
|
31
|
+
export function formatTime(value, options = {}) {
|
|
32
|
+
const { locale, timeZone } = readOptions(options);
|
|
33
|
+
return formatterFor("time", locale, timeZone).format(toInstant(value));
|
|
34
|
+
}
|
|
35
|
+
/** Localized calendar date; it is anchored to UTC so the day never shifts. */
|
|
36
|
+
export function formatDateOnly(value, options = {}) {
|
|
37
|
+
const { locale } = readOptions(options);
|
|
38
|
+
return formatterFor("calendar-date", locale, undefined).format(utcDateFromParts(parseDateOnly(value)));
|
|
39
|
+
}
|
|
40
|
+
function readOptions(options) {
|
|
41
|
+
// Public parameters are typed, but generated projects are plain JS: validating the options
|
|
42
|
+
// object turns a wrong call into a clear TypeError instead of a random crash.
|
|
43
|
+
if (options === null || typeof options !== "object") {
|
|
44
|
+
throw new TypeError("@facilis.dev/time: options must be an object, received " + describeValue(options));
|
|
45
|
+
}
|
|
46
|
+
const candidate = options;
|
|
47
|
+
if (candidate.locale !== undefined && typeof candidate.locale !== "string") {
|
|
48
|
+
throw new TypeError('@facilis.dev/time: "locale" must be a string, received ' + describeValue(candidate.locale));
|
|
49
|
+
}
|
|
50
|
+
if (candidate.timeZone !== undefined && typeof candidate.timeZone !== "string") {
|
|
51
|
+
throw new TypeError('@facilis.dev/time: "timeZone" must be a string, received ' + describeValue(candidate.timeZone));
|
|
52
|
+
}
|
|
53
|
+
return { locale: candidate.locale, timeZone: candidate.timeZone };
|
|
54
|
+
}
|
|
55
|
+
function formatterFor(kind, locale, timeZone) {
|
|
56
|
+
const key = kind + "|" + (locale ?? "") + "|" + (timeZone ?? "");
|
|
57
|
+
let formatter = FORMATTERS.get(key);
|
|
58
|
+
if (formatter === undefined) {
|
|
59
|
+
if (FORMATTERS.size >= MAX_CACHED_FORMATTERS)
|
|
60
|
+
FORMATTERS.clear();
|
|
61
|
+
const options = { ...STYLES[kind] };
|
|
62
|
+
// Calendar days are anchored to UTC; every other kind uses the caller's zone or the runtime
|
|
63
|
+
// default, which is what undefined means to Intl.
|
|
64
|
+
options.timeZone = kind === "calendar-date" ? "UTC" : timeZone;
|
|
65
|
+
formatter = new Intl.DateTimeFormat(locale, options);
|
|
66
|
+
FORMATTERS.set(key, formatter);
|
|
67
|
+
}
|
|
68
|
+
return formatter;
|
|
69
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @facilis.dev/time - zero-dependency date/time logic for generated projects.
|
|
3
|
+
*
|
|
4
|
+
* A flat, named surface: formatting with an explicit locale and time zone, calendar days as
|
|
5
|
+
* YYYY-MM-DD strings, and DST-aware day boundaries. There is nothing to configure - import the
|
|
6
|
+
* functions the project uses.
|
|
7
|
+
*/
|
|
8
|
+
export type { DateInput } from "./instant.js";
|
|
9
|
+
export { dateOnlyOf, today } from "./calendar.js";
|
|
10
|
+
export { isValidDateOnly } from "./date-only.js";
|
|
11
|
+
export { endOfDay, startOfDay } from "./day-bounds.js";
|
|
12
|
+
export { formatDate, formatDateOnly, formatDateTime, formatTime } from "./format.js";
|
|
13
|
+
export type { DateOnlyFormatOptions, FormatOptions } from "./format.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @facilis.dev/time - zero-dependency date/time logic for generated projects.
|
|
3
|
+
*
|
|
4
|
+
* A flat, named surface: formatting with an explicit locale and time zone, calendar days as
|
|
5
|
+
* YYYY-MM-DD strings, and DST-aware day boundaries. There is nothing to configure - import the
|
|
6
|
+
* functions the project uses.
|
|
7
|
+
*/
|
|
8
|
+
export { dateOnlyOf, today } from "./calendar.js";
|
|
9
|
+
export { isValidDateOnly } from "./date-only.js";
|
|
10
|
+
export { endOfDay, startOfDay } from "./day-bounds.js";
|
|
11
|
+
export { formatDate, formatDateOnly, formatDateTime, formatTime } from "./format.js";
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Instant coercion.
|
|
3
|
+
*
|
|
4
|
+
* The package accepts Date objects and ISO 8601 strings only. A date-time string without an
|
|
5
|
+
* offset is rejected on purpose: new Date("2026-03-29T12:00:00") is parsed in the runtime zone,
|
|
6
|
+
* which would silently contradict the explicit-timeZone contract of every formatter.
|
|
7
|
+
*/
|
|
8
|
+
/** An instant: a Date object or an ISO 8601 date/date-time string. */
|
|
9
|
+
export type DateInput = Date | string;
|
|
10
|
+
/** Throws for anything that is not a Date or an ISO 8601 instant. */
|
|
11
|
+
export declare function toInstant(value: DateInput): Date;
|
package/dist/instant.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Instant coercion.
|
|
3
|
+
*
|
|
4
|
+
* The package accepts Date objects and ISO 8601 strings only. A date-time string without an
|
|
5
|
+
* offset is rejected on purpose: new Date("2026-03-29T12:00:00") is parsed in the runtime zone,
|
|
6
|
+
* which would silently contradict the explicit-timeZone contract of every formatter.
|
|
7
|
+
*/
|
|
8
|
+
import { describeValue } from "./describe-value.js";
|
|
9
|
+
import { isRealCalendarDate, utcDateFromParts } from "./date-only.js";
|
|
10
|
+
const ISO_INSTANT_PATTERN = /^(\d{4})-(\d{2})-(\d{2})(?:[Tt ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?([Zz]|[+-]\d{2}:\d{2}))?$/;
|
|
11
|
+
/** Throws for anything that is not a Date or an ISO 8601 instant. */
|
|
12
|
+
export function toInstant(value) {
|
|
13
|
+
if (value instanceof Date) {
|
|
14
|
+
// An invalid Date carries no instant; copying keeps the caller's object untouched.
|
|
15
|
+
if (Number.isNaN(value.getTime())) {
|
|
16
|
+
throw new RangeError("@facilis.dev/time: received an invalid Date");
|
|
17
|
+
}
|
|
18
|
+
return new Date(value.getTime());
|
|
19
|
+
}
|
|
20
|
+
if (typeof value !== "string") {
|
|
21
|
+
throw new TypeError("@facilis.dev/time: expected a Date or ISO 8601 string, received " + describeValue(value));
|
|
22
|
+
}
|
|
23
|
+
const match = ISO_INSTANT_PATTERN.exec(value);
|
|
24
|
+
if (match === null) {
|
|
25
|
+
throw new RangeError('@facilis.dev/time: "' +
|
|
26
|
+
value +
|
|
27
|
+
'" is not an ISO 8601 date or date-time (a time requires a Z or +-hh:mm offset)');
|
|
28
|
+
}
|
|
29
|
+
const year = Number(match[1]);
|
|
30
|
+
const month = Number(match[2]);
|
|
31
|
+
const day = Number(match[3]);
|
|
32
|
+
if (!isRealCalendarDate(year, month, day)) {
|
|
33
|
+
throw new RangeError('@facilis.dev/time: "' + value + '" is not a real calendar date');
|
|
34
|
+
}
|
|
35
|
+
const hour = readField(match[4]);
|
|
36
|
+
const minute = readField(match[5]);
|
|
37
|
+
const second = readField(match[6]);
|
|
38
|
+
if (hour > 23 || minute > 59 || second > 59) {
|
|
39
|
+
throw new RangeError('@facilis.dev/time: "' + value + '" is not a valid time of day');
|
|
40
|
+
}
|
|
41
|
+
const millisecond = match[7] === undefined ? 0 : Number(match[7].padEnd(3, "0"));
|
|
42
|
+
const utcMs = utcDateFromParts({ year, month, day, hour, minute, second, millisecond }).getTime();
|
|
43
|
+
// A date-only string names no zone; ISO 8601 (and Date.parse) read it as UTC midnight, which
|
|
44
|
+
// keeps the instant independent of the runtime zone.
|
|
45
|
+
return new Date(utcMs - offsetMs(match[8]));
|
|
46
|
+
}
|
|
47
|
+
function readField(value) {
|
|
48
|
+
return value === undefined ? 0 : Number(value);
|
|
49
|
+
}
|
|
50
|
+
function offsetMs(offset) {
|
|
51
|
+
if (offset === undefined || offset === "Z" || offset === "z")
|
|
52
|
+
return 0;
|
|
53
|
+
const sign = offset.startsWith("-") ? -1 : 1;
|
|
54
|
+
const hours = Number(offset.slice(1, 3));
|
|
55
|
+
const minutes = Number(offset.slice(4, 6));
|
|
56
|
+
if (hours > 23 || minutes > 59) {
|
|
57
|
+
throw new RangeError('@facilis.dev/time: "' + offset + '" is not a valid UTC offset');
|
|
58
|
+
}
|
|
59
|
+
return sign * (hours * 60 + minutes) * 60_000;
|
|
60
|
+
}
|
package/dist/zone.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Intl primitives for an explicit IANA time zone.
|
|
3
|
+
*
|
|
4
|
+
* The runtime zone is used only when a caller omits the zone; every helper takes the resolved
|
|
5
|
+
* zone explicitly so the public functions can document a single default.
|
|
6
|
+
*/
|
|
7
|
+
/** Wall-clock fields an instant shows in a zone, plus the era token for range checks. */
|
|
8
|
+
export interface WallParts {
|
|
9
|
+
year: number;
|
|
10
|
+
month: number;
|
|
11
|
+
day: number;
|
|
12
|
+
hour: number;
|
|
13
|
+
minute: number;
|
|
14
|
+
second: number;
|
|
15
|
+
era: string;
|
|
16
|
+
}
|
|
17
|
+
/** The date and time fields used to compare two wall clocks. */
|
|
18
|
+
export type WallTime = Pick<WallParts, "year" | "month" | "day" | "hour" | "minute" | "second">;
|
|
19
|
+
/** Rejects non-string zones up front; a syntactically invalid zone throws RangeError from Intl. */
|
|
20
|
+
export declare function assertTimeZone(timeZone: unknown): asserts timeZone is string;
|
|
21
|
+
/** Like assertTimeZone, but the omitted runtime-zone default is allowed. */
|
|
22
|
+
export declare function assertOptionalTimeZone(timeZone: unknown): asserts timeZone is string | undefined;
|
|
23
|
+
/** The wall-clock fields an instant shows in a zone (defaults to the runtime zone). */
|
|
24
|
+
export declare function wallPartsAt(instantMs: number, timeZone: string | undefined): WallParts;
|
|
25
|
+
/** Offset of the zone at an instant, in milliseconds (local wall time minus UTC). */
|
|
26
|
+
export declare function zoneOffsetMs(instantMs: number, timeZone: string | undefined): number;
|
|
27
|
+
/** Whether two wall clocks name the same local date and time (the era is metadata, not time). */
|
|
28
|
+
export declare function isSameWallTime(left: WallTime, right: WallTime): boolean;
|
package/dist/zone.js
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Intl primitives for an explicit IANA time zone.
|
|
3
|
+
*
|
|
4
|
+
* The runtime zone is used only when a caller omits the zone; every helper takes the resolved
|
|
5
|
+
* zone explicitly so the public functions can document a single default.
|
|
6
|
+
*/
|
|
7
|
+
import { describeValue } from "./describe-value.js";
|
|
8
|
+
import { utcDateFromParts } from "./date-only.js";
|
|
9
|
+
// Locale, numbering system and calendar are pinned so the parts are ASCII numbers of the
|
|
10
|
+
// proleptic Gregorian calendar whatever the runtime locale is. ICU's Gregorian calendar matches
|
|
11
|
+
// ISO 8601 for years 0001-9999, and the era part is what lets dateOnlyOf reject BCE instants.
|
|
12
|
+
const WALL_FORMAT_OPTIONS = {
|
|
13
|
+
year: "numeric",
|
|
14
|
+
month: "2-digit",
|
|
15
|
+
day: "2-digit",
|
|
16
|
+
hour: "2-digit",
|
|
17
|
+
minute: "2-digit",
|
|
18
|
+
second: "2-digit",
|
|
19
|
+
hourCycle: "h23",
|
|
20
|
+
calendar: "gregory",
|
|
21
|
+
numberingSystem: "latn",
|
|
22
|
+
era: "short",
|
|
23
|
+
};
|
|
24
|
+
// Formatter construction dominates Intl formatting cost and an app uses one or two zones; the
|
|
25
|
+
// cap keeps caller-supplied values from growing the cache without bound.
|
|
26
|
+
const MAX_CACHED_FORMATTERS = 64;
|
|
27
|
+
const WALL_FORMATTERS = new Map();
|
|
28
|
+
function wallFormatterFor(timeZone) {
|
|
29
|
+
const key = timeZone ?? "";
|
|
30
|
+
let formatter = WALL_FORMATTERS.get(key);
|
|
31
|
+
if (formatter === undefined) {
|
|
32
|
+
if (WALL_FORMATTERS.size >= MAX_CACHED_FORMATTERS)
|
|
33
|
+
WALL_FORMATTERS.clear();
|
|
34
|
+
formatter = new Intl.DateTimeFormat("en-US", {
|
|
35
|
+
...WALL_FORMAT_OPTIONS,
|
|
36
|
+
...(timeZone === undefined ? {} : { timeZone }),
|
|
37
|
+
});
|
|
38
|
+
WALL_FORMATTERS.set(key, formatter);
|
|
39
|
+
}
|
|
40
|
+
return formatter;
|
|
41
|
+
}
|
|
42
|
+
/** Rejects non-string zones up front; a syntactically invalid zone throws RangeError from Intl. */
|
|
43
|
+
export function assertTimeZone(timeZone) {
|
|
44
|
+
if (typeof timeZone !== "string") {
|
|
45
|
+
throw new TypeError("@facilis.dev/time: expected a time zone string, received " + describeValue(timeZone));
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/** Like assertTimeZone, but the omitted runtime-zone default is allowed. */
|
|
49
|
+
export function assertOptionalTimeZone(timeZone) {
|
|
50
|
+
if (timeZone !== undefined && typeof timeZone !== "string") {
|
|
51
|
+
throw new TypeError("@facilis.dev/time: expected a time zone string, received " + describeValue(timeZone));
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/** The wall-clock fields an instant shows in a zone (defaults to the runtime zone). */
|
|
55
|
+
export function wallPartsAt(instantMs, timeZone) {
|
|
56
|
+
assertOptionalTimeZone(timeZone);
|
|
57
|
+
const values = new Map();
|
|
58
|
+
for (const part of wallFormatterFor(timeZone).formatToParts(new Date(instantMs))) {
|
|
59
|
+
values.set(part.type, part.value);
|
|
60
|
+
}
|
|
61
|
+
return {
|
|
62
|
+
year: readNumberPart(values, "year"),
|
|
63
|
+
month: readNumberPart(values, "month"),
|
|
64
|
+
day: readNumberPart(values, "day"),
|
|
65
|
+
hour: readNumberPart(values, "hour"),
|
|
66
|
+
minute: readNumberPart(values, "minute"),
|
|
67
|
+
second: readNumberPart(values, "second"),
|
|
68
|
+
era: readTextPart(values, "era"),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/** Offset of the zone at an instant, in milliseconds (local wall time minus UTC). */
|
|
72
|
+
export function zoneOffsetMs(instantMs, timeZone) {
|
|
73
|
+
// Whole seconds keep the subtraction exact; UTC offsets never carry a fraction of a second.
|
|
74
|
+
const floored = Math.floor(instantMs / 1000) * 1000;
|
|
75
|
+
return utcDateFromParts(wallPartsAt(floored, timeZone)).getTime() - floored;
|
|
76
|
+
}
|
|
77
|
+
/** Whether two wall clocks name the same local date and time (the era is metadata, not time). */
|
|
78
|
+
export function isSameWallTime(left, right) {
|
|
79
|
+
return (left.year === right.year &&
|
|
80
|
+
left.month === right.month &&
|
|
81
|
+
left.day === right.day &&
|
|
82
|
+
left.hour === right.hour &&
|
|
83
|
+
left.minute === right.minute &&
|
|
84
|
+
left.second === right.second);
|
|
85
|
+
}
|
|
86
|
+
function readNumberPart(values, type) {
|
|
87
|
+
return Number(readTextPart(values, type));
|
|
88
|
+
}
|
|
89
|
+
function readTextPart(values, type) {
|
|
90
|
+
const value = values.get(type);
|
|
91
|
+
if (value === undefined) {
|
|
92
|
+
// WALL_FORMAT_OPTIONS fixes the part set, so a missing part is an Intl contract violation.
|
|
93
|
+
throw new Error('@facilis.dev/time: Intl.DateTimeFormat did not return the "' + type + '" part');
|
|
94
|
+
}
|
|
95
|
+
return value;
|
|
96
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,41 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@facilis.dev/time",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Facilis date/time logic: zero-dependency, Intl-based formatting and calendar-day handling with explicit time zones.",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./dist/index.js",
|
|
9
|
+
"./package.json": "./package.json"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"dist",
|
|
13
|
+
"src",
|
|
14
|
+
"README.md",
|
|
15
|
+
"LICENSE"
|
|
16
|
+
],
|
|
17
|
+
"engines": {
|
|
18
|
+
"node": ">=22.15.0"
|
|
19
|
+
},
|
|
20
|
+
"publishConfig": {
|
|
21
|
+
"access": "public"
|
|
22
|
+
},
|
|
23
|
+
"repository": {
|
|
24
|
+
"type": "git",
|
|
25
|
+
"url": "git+https://github.com/facilis-dev/facilis.git",
|
|
26
|
+
"directory": "packages/time"
|
|
27
|
+
},
|
|
28
|
+
"homepage": "https://github.com/facilis-dev/facilis/tree/main/packages/time#readme",
|
|
29
|
+
"bugs": {
|
|
30
|
+
"url": "https://github.com/facilis-dev/facilis/issues"
|
|
31
|
+
},
|
|
32
|
+
"keywords": [
|
|
33
|
+
"facilis",
|
|
34
|
+
"framework",
|
|
35
|
+
"vite",
|
|
36
|
+
"nitro",
|
|
37
|
+
"low-code"
|
|
38
|
+
],
|
|
39
|
+
"main": "./dist/index.js",
|
|
40
|
+
"types": "./dist/index.d.ts"
|
|
41
|
+
}
|
package/src/calendar.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The calendar day of an instant, read in an explicit zone.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { serializeDateOnly } from "./date-only.ts";
|
|
6
|
+
import { toInstant, type DateInput } from "./instant.ts";
|
|
7
|
+
import { wallPartsAt, type WallParts } from "./zone.ts";
|
|
8
|
+
|
|
9
|
+
/** The YYYY-MM-DD the instant falls on in the zone (defaults to the runtime zone). */
|
|
10
|
+
export function dateOnlyOf(value: DateInput, timeZone?: string): string {
|
|
11
|
+
const instant = toInstant(value);
|
|
12
|
+
const parts = wallPartsAt(instant.getTime(), timeZone);
|
|
13
|
+
assertCalendarDayRange(parts);
|
|
14
|
+
return serializeDateOnly(parts);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** dateOnlyOf(now, timeZone) - "today" always means "today in that zone". */
|
|
18
|
+
export function today(timeZone?: string, now: DateInput = new Date()): string {
|
|
19
|
+
return dateOnlyOf(now, timeZone);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function assertCalendarDayRange(parts: WallParts): void {
|
|
23
|
+
// The pinned gregory formatter reports BCE years as positive numbers with a "BC" era; neither
|
|
24
|
+
// those nor years above 9999 can be written as a YYYY-MM-DD calendar day.
|
|
25
|
+
if (parts.era === "BC" || parts.year < 1 || parts.year > 9999) {
|
|
26
|
+
throw new RangeError("@facilis.dev/time: the instant is outside the supported calendar-day range");
|
|
27
|
+
}
|
|
28
|
+
}
|
package/src/date-only.ts
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Calendar-day ("YYYY-MM-DD") values.
|
|
3
|
+
*
|
|
4
|
+
* A calendar day is a plain string in this package: it names no instant and no zone, so it must
|
|
5
|
+
* never be routed through a Date in the runtime zone (that is exactly how date pickers shift a
|
|
6
|
+
* day). All arithmetic here is on the proleptic Gregorian calendar, years 0001-9999.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { describeValue } from "./describe-value.ts";
|
|
10
|
+
|
|
11
|
+
const DATE_ONLY_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
12
|
+
|
|
13
|
+
/** Days per month in a non-leap year; February is handled by isRealCalendarDate. */
|
|
14
|
+
const DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const;
|
|
15
|
+
|
|
16
|
+
export interface DateOnlyParts {
|
|
17
|
+
year: number;
|
|
18
|
+
month: number;
|
|
19
|
+
day: number;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Wall-clock fields of a local time; fields below the hour are optional. */
|
|
23
|
+
export interface DateTimeParts extends DateOnlyParts {
|
|
24
|
+
hour?: number;
|
|
25
|
+
minute?: number;
|
|
26
|
+
second?: number;
|
|
27
|
+
millisecond?: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function isLeapYear(year: number): boolean {
|
|
31
|
+
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Whether the fields name a date in the proleptic Gregorian calendar (no year range check). */
|
|
35
|
+
export function isRealCalendarDate(year: number, month: number, day: number): boolean {
|
|
36
|
+
if (month < 1 || month > 12 || day < 1) return false;
|
|
37
|
+
const longestDay = month === 2 && isLeapYear(year) ? 29 : (DAYS_IN_MONTH[month - 1] ?? 0);
|
|
38
|
+
return day <= longestDay;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Parses a YYYY-MM-DD calendar day, throwing for everything else.
|
|
43
|
+
*
|
|
44
|
+
* This is the single source of truth for the format: isValidDateOnly is this parser inside a
|
|
45
|
+
* try/catch, so the validator and the consumers cannot drift apart.
|
|
46
|
+
*/
|
|
47
|
+
export function parseDateOnly(value: unknown): DateOnlyParts {
|
|
48
|
+
if (typeof value !== "string") {
|
|
49
|
+
throw new TypeError(
|
|
50
|
+
"@facilis.dev/time: expected a YYYY-MM-DD string, received " + describeValue(value),
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
const match = DATE_ONLY_PATTERN.exec(value);
|
|
54
|
+
if (match === null) {
|
|
55
|
+
throw new RangeError('@facilis.dev/time: "' + value + '" is not a YYYY-MM-DD calendar date');
|
|
56
|
+
}
|
|
57
|
+
const year = Number(match[1]);
|
|
58
|
+
const month = Number(match[2]);
|
|
59
|
+
const day = Number(match[3]);
|
|
60
|
+
if (year < 1 || year > 9999 || !isRealCalendarDate(year, month, day)) {
|
|
61
|
+
throw new RangeError(
|
|
62
|
+
'@facilis.dev/time: "' +
|
|
63
|
+
value +
|
|
64
|
+
'" is not a real calendar date between 0001-01-01 and 9999-12-31',
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
return { year, month, day };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Strict guard for the calendar-day contract; non-strings are not dates rather than errors. */
|
|
71
|
+
export function isValidDateOnly(value: unknown): value is string {
|
|
72
|
+
try {
|
|
73
|
+
parseDateOnly(value);
|
|
74
|
+
return true;
|
|
75
|
+
} catch {
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Serializes calendar fields as YYYY-MM-DD; callers pass an already valid date. */
|
|
81
|
+
export function serializeDateOnly(parts: DateOnlyParts): string {
|
|
82
|
+
return pad(parts.year, 4) + "-" + pad(parts.month, 2) + "-" + pad(parts.day, 2);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* UTC instant of the given wall-clock fields.
|
|
87
|
+
*
|
|
88
|
+
* Date.UTC maps years 0-99 to 1900-1999, so the fields are applied with setUTCFullYear instead;
|
|
89
|
+
* that is what keeps 0001-01-01 and 9999-12-31 correct.
|
|
90
|
+
*/
|
|
91
|
+
export function utcDateFromParts(parts: DateTimeParts): Date {
|
|
92
|
+
const date = new Date(0);
|
|
93
|
+
date.setUTCFullYear(parts.year, parts.month - 1, parts.day);
|
|
94
|
+
date.setUTCHours(parts.hour ?? 0, parts.minute ?? 0, parts.second ?? 0, parts.millisecond ?? 0);
|
|
95
|
+
return date;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Calendar-day arithmetic, with month and year roll-over. */
|
|
99
|
+
export function addDays(parts: DateOnlyParts, days: number): DateOnlyParts {
|
|
100
|
+
const date = utcDateFromParts({ ...parts, day: parts.day + days });
|
|
101
|
+
return { year: date.getUTCFullYear(), month: date.getUTCMonth() + 1, day: date.getUTCDate() };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function pad(value: number, length: number): string {
|
|
105
|
+
return String(value).padStart(length, "0");
|
|
106
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The UTC instants at which a local calendar day starts and ends.
|
|
3
|
+
*
|
|
4
|
+
* Boundaries are anchored on local midnight and computed by probing the zone offset instead of
|
|
5
|
+
* adding to a naive local time: a DST day can be 23 or 25 hours long, so only the wall clock
|
|
6
|
+
* and the zone offset tell the truth.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { addDays, parseDateOnly, utcDateFromParts, type DateOnlyParts } from "./date-only.ts";
|
|
10
|
+
import {
|
|
11
|
+
assertTimeZone,
|
|
12
|
+
isSameWallTime,
|
|
13
|
+
wallPartsAt,
|
|
14
|
+
zoneOffsetMs,
|
|
15
|
+
type WallTime,
|
|
16
|
+
} from "./zone.ts";
|
|
17
|
+
|
|
18
|
+
/** UTC instant of local 00:00 on the calendar day in the zone (DST-aware). */
|
|
19
|
+
export function startOfDay(dateOnly: string, timeZone: string): Date {
|
|
20
|
+
assertTimeZone(timeZone);
|
|
21
|
+
return new Date(startOfDayMs(parseDateOnly(dateOnly), timeZone));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** UTC instant of local 23:59:59.999 on the calendar day in the zone (DST-aware). */
|
|
25
|
+
export function endOfDay(dateOnly: string, timeZone: string): Date {
|
|
26
|
+
assertTimeZone(timeZone);
|
|
27
|
+
// The first millisecond of the next local day is a day's exclusive end in every zone, and
|
|
28
|
+
// subtracting one also handles a day whose final local second the zone skips.
|
|
29
|
+
return new Date(startOfDayMs(addDays(parseDateOnly(dateOnly), 1), timeZone) - 1);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function startOfDayMs(dateOnly: DateOnlyParts, timeZone: string): number {
|
|
33
|
+
const midnight: WallTime = {
|
|
34
|
+
year: dateOnly.year,
|
|
35
|
+
month: dateOnly.month,
|
|
36
|
+
day: dateOnly.day,
|
|
37
|
+
hour: 0,
|
|
38
|
+
minute: 0,
|
|
39
|
+
second: 0,
|
|
40
|
+
};
|
|
41
|
+
// The instant of a wall-clock time is not a function of that time alone: a DST transition can
|
|
42
|
+
// repeat it or skip it, so the offset is probed on both sides of the naive instant.
|
|
43
|
+
const naive = utcDateFromParts(midnight).getTime();
|
|
44
|
+
const firstProbe = naive - zoneOffsetMs(naive, timeZone);
|
|
45
|
+
const secondProbe = naive - zoneOffsetMs(firstProbe, timeZone);
|
|
46
|
+
const candidates = [firstProbe, secondProbe].filter((candidate) =>
|
|
47
|
+
isSameWallTime(wallPartsAt(candidate, timeZone), midnight),
|
|
48
|
+
);
|
|
49
|
+
// Repeated local midnight (fall back): pick the earliest occurrence, so startOfDay - 1 ms is
|
|
50
|
+
// still the previous day. Skipped local midnight (spring forward): the day starts at the
|
|
51
|
+
// transition, which is the later probe.
|
|
52
|
+
return candidates.length > 0 ? Math.min(...candidates) : Math.max(firstProbe, secondProbe);
|
|
53
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Renders an unexpected value for an error message.
|
|
3
|
+
*
|
|
4
|
+
* typeof alone says "object" for null and arrays, which is exactly the confusion the TypeError
|
|
5
|
+
* messages exist to clear up.
|
|
6
|
+
*/
|
|
7
|
+
export function describeValue(value: unknown): string {
|
|
8
|
+
if (value === null) return "null";
|
|
9
|
+
if (Array.isArray(value)) return "an array";
|
|
10
|
+
return typeof value;
|
|
11
|
+
}
|
package/src/format.ts
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Localized formatting with an explicit locale and time zone.
|
|
3
|
+
*
|
|
4
|
+
* The style is fixed per function (medium date, short time) so a project gets one stable look
|
|
5
|
+
* without a prop surface; anything richer is "copy the function and pick the style".
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { describeValue } from "./describe-value.ts";
|
|
9
|
+
import { parseDateOnly, utcDateFromParts } from "./date-only.ts";
|
|
10
|
+
import { toInstant, type DateInput } from "./instant.ts";
|
|
11
|
+
|
|
12
|
+
/** Locale and zone for the instant formatters; both default to the runtime values. */
|
|
13
|
+
export interface FormatOptions {
|
|
14
|
+
/** BCP 47 locale tag. */
|
|
15
|
+
locale?: string;
|
|
16
|
+
/** IANA time zone name. */
|
|
17
|
+
timeZone?: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Calendar days have no zone, so only the locale applies. */
|
|
21
|
+
export interface DateOnlyFormatOptions {
|
|
22
|
+
locale?: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
type FormatKind = "date" | "date-time" | "time" | "calendar-date";
|
|
26
|
+
|
|
27
|
+
const STYLES: Record<FormatKind, Intl.DateTimeFormatOptions> = {
|
|
28
|
+
date: { dateStyle: "medium" },
|
|
29
|
+
"date-time": { dateStyle: "medium", timeStyle: "short" },
|
|
30
|
+
time: { timeStyle: "short" },
|
|
31
|
+
"calendar-date": { dateStyle: "medium" },
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
// Formatter construction dominates Intl formatting cost and an app uses a couple of
|
|
35
|
+
// locale/zone pairs; the cap keeps caller-supplied values from growing the cache without bound.
|
|
36
|
+
const MAX_CACHED_FORMATTERS = 64;
|
|
37
|
+
const FORMATTERS = new Map<string, Intl.DateTimeFormat>();
|
|
38
|
+
|
|
39
|
+
/** Localized date (medium style) in the requested zone. */
|
|
40
|
+
export function formatDate(value: DateInput, options: FormatOptions = {}): string {
|
|
41
|
+
const { locale, timeZone } = readOptions(options);
|
|
42
|
+
return formatterFor("date", locale, timeZone).format(toInstant(value));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Localized date and time in the requested zone. */
|
|
46
|
+
export function formatDateTime(value: DateInput, options: FormatOptions = {}): string {
|
|
47
|
+
const { locale, timeZone } = readOptions(options);
|
|
48
|
+
return formatterFor("date-time", locale, timeZone).format(toInstant(value));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Localized time in the requested zone. */
|
|
52
|
+
export function formatTime(value: DateInput, options: FormatOptions = {}): string {
|
|
53
|
+
const { locale, timeZone } = readOptions(options);
|
|
54
|
+
return formatterFor("time", locale, timeZone).format(toInstant(value));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Localized calendar date; it is anchored to UTC so the day never shifts. */
|
|
58
|
+
export function formatDateOnly(value: string, options: DateOnlyFormatOptions = {}): string {
|
|
59
|
+
const { locale } = readOptions(options);
|
|
60
|
+
return formatterFor("calendar-date", locale, undefined).format(
|
|
61
|
+
utcDateFromParts(parseDateOnly(value)),
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
interface ResolvedOptions {
|
|
66
|
+
locale: string | undefined;
|
|
67
|
+
timeZone: string | undefined;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function readOptions(options: unknown): ResolvedOptions {
|
|
71
|
+
// Public parameters are typed, but generated projects are plain JS: validating the options
|
|
72
|
+
// object turns a wrong call into a clear TypeError instead of a random crash.
|
|
73
|
+
if (options === null || typeof options !== "object") {
|
|
74
|
+
throw new TypeError(
|
|
75
|
+
"@facilis.dev/time: options must be an object, received " + describeValue(options),
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
const candidate = options as { locale?: unknown; timeZone?: unknown };
|
|
79
|
+
if (candidate.locale !== undefined && typeof candidate.locale !== "string") {
|
|
80
|
+
throw new TypeError(
|
|
81
|
+
'@facilis.dev/time: "locale" must be a string, received ' + describeValue(candidate.locale),
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
if (candidate.timeZone !== undefined && typeof candidate.timeZone !== "string") {
|
|
85
|
+
throw new TypeError(
|
|
86
|
+
'@facilis.dev/time: "timeZone" must be a string, received ' + describeValue(candidate.timeZone),
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
return { locale: candidate.locale, timeZone: candidate.timeZone };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function formatterFor(
|
|
93
|
+
kind: FormatKind,
|
|
94
|
+
locale: string | undefined,
|
|
95
|
+
timeZone: string | undefined,
|
|
96
|
+
): Intl.DateTimeFormat {
|
|
97
|
+
const key = kind + "|" + (locale ?? "") + "|" + (timeZone ?? "");
|
|
98
|
+
let formatter = FORMATTERS.get(key);
|
|
99
|
+
if (formatter === undefined) {
|
|
100
|
+
if (FORMATTERS.size >= MAX_CACHED_FORMATTERS) FORMATTERS.clear();
|
|
101
|
+
const options: Intl.DateTimeFormatOptions = { ...STYLES[kind] };
|
|
102
|
+
// Calendar days are anchored to UTC; every other kind uses the caller's zone or the runtime
|
|
103
|
+
// default, which is what undefined means to Intl.
|
|
104
|
+
options.timeZone = kind === "calendar-date" ? "UTC" : timeZone;
|
|
105
|
+
formatter = new Intl.DateTimeFormat(locale, options);
|
|
106
|
+
FORMATTERS.set(key, formatter);
|
|
107
|
+
}
|
|
108
|
+
return formatter;
|
|
109
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @facilis.dev/time - zero-dependency date/time logic for generated projects.
|
|
3
|
+
*
|
|
4
|
+
* A flat, named surface: formatting with an explicit locale and time zone, calendar days as
|
|
5
|
+
* YYYY-MM-DD strings, and DST-aware day boundaries. There is nothing to configure - import the
|
|
6
|
+
* functions the project uses.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export type { DateInput } from "./instant.ts";
|
|
10
|
+
|
|
11
|
+
export { dateOnlyOf, today } from "./calendar.ts";
|
|
12
|
+
export { isValidDateOnly } from "./date-only.ts";
|
|
13
|
+
export { endOfDay, startOfDay } from "./day-bounds.ts";
|
|
14
|
+
export { formatDate, formatDateOnly, formatDateTime, formatTime } from "./format.ts";
|
|
15
|
+
export type { DateOnlyFormatOptions, FormatOptions } from "./format.ts";
|
package/src/instant.ts
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Instant coercion.
|
|
3
|
+
*
|
|
4
|
+
* The package accepts Date objects and ISO 8601 strings only. A date-time string without an
|
|
5
|
+
* offset is rejected on purpose: new Date("2026-03-29T12:00:00") is parsed in the runtime zone,
|
|
6
|
+
* which would silently contradict the explicit-timeZone contract of every formatter.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { describeValue } from "./describe-value.ts";
|
|
10
|
+
import { isRealCalendarDate, utcDateFromParts } from "./date-only.ts";
|
|
11
|
+
|
|
12
|
+
/** An instant: a Date object or an ISO 8601 date/date-time string. */
|
|
13
|
+
export type DateInput = Date | string;
|
|
14
|
+
|
|
15
|
+
const ISO_INSTANT_PATTERN =
|
|
16
|
+
/^(\d{4})-(\d{2})-(\d{2})(?:[Tt ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?([Zz]|[+-]\d{2}:\d{2}))?$/;
|
|
17
|
+
|
|
18
|
+
/** Throws for anything that is not a Date or an ISO 8601 instant. */
|
|
19
|
+
export function toInstant(value: DateInput): Date {
|
|
20
|
+
if (value instanceof Date) {
|
|
21
|
+
// An invalid Date carries no instant; copying keeps the caller's object untouched.
|
|
22
|
+
if (Number.isNaN(value.getTime())) {
|
|
23
|
+
throw new RangeError("@facilis.dev/time: received an invalid Date");
|
|
24
|
+
}
|
|
25
|
+
return new Date(value.getTime());
|
|
26
|
+
}
|
|
27
|
+
if (typeof value !== "string") {
|
|
28
|
+
throw new TypeError(
|
|
29
|
+
"@facilis.dev/time: expected a Date or ISO 8601 string, received " + describeValue(value),
|
|
30
|
+
);
|
|
31
|
+
}
|
|
32
|
+
const match = ISO_INSTANT_PATTERN.exec(value);
|
|
33
|
+
if (match === null) {
|
|
34
|
+
throw new RangeError(
|
|
35
|
+
'@facilis.dev/time: "' +
|
|
36
|
+
value +
|
|
37
|
+
'" is not an ISO 8601 date or date-time (a time requires a Z or +-hh:mm offset)',
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
const year = Number(match[1]);
|
|
41
|
+
const month = Number(match[2]);
|
|
42
|
+
const day = Number(match[3]);
|
|
43
|
+
if (!isRealCalendarDate(year, month, day)) {
|
|
44
|
+
throw new RangeError('@facilis.dev/time: "' + value + '" is not a real calendar date');
|
|
45
|
+
}
|
|
46
|
+
const hour = readField(match[4]);
|
|
47
|
+
const minute = readField(match[5]);
|
|
48
|
+
const second = readField(match[6]);
|
|
49
|
+
if (hour > 23 || minute > 59 || second > 59) {
|
|
50
|
+
throw new RangeError('@facilis.dev/time: "' + value + '" is not a valid time of day');
|
|
51
|
+
}
|
|
52
|
+
const millisecond = match[7] === undefined ? 0 : Number(match[7].padEnd(3, "0"));
|
|
53
|
+
const utcMs = utcDateFromParts({ year, month, day, hour, minute, second, millisecond }).getTime();
|
|
54
|
+
// A date-only string names no zone; ISO 8601 (and Date.parse) read it as UTC midnight, which
|
|
55
|
+
// keeps the instant independent of the runtime zone.
|
|
56
|
+
return new Date(utcMs - offsetMs(match[8]));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function readField(value: string | undefined): number {
|
|
60
|
+
return value === undefined ? 0 : Number(value);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function offsetMs(offset: string | undefined): number {
|
|
64
|
+
if (offset === undefined || offset === "Z" || offset === "z") return 0;
|
|
65
|
+
const sign = offset.startsWith("-") ? -1 : 1;
|
|
66
|
+
const hours = Number(offset.slice(1, 3));
|
|
67
|
+
const minutes = Number(offset.slice(4, 6));
|
|
68
|
+
if (hours > 23 || minutes > 59) {
|
|
69
|
+
throw new RangeError('@facilis.dev/time: "' + offset + '" is not a valid UTC offset');
|
|
70
|
+
}
|
|
71
|
+
return sign * (hours * 60 + minutes) * 60_000;
|
|
72
|
+
}
|
package/src/zone.ts
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Intl primitives for an explicit IANA time zone.
|
|
3
|
+
*
|
|
4
|
+
* The runtime zone is used only when a caller omits the zone; every helper takes the resolved
|
|
5
|
+
* zone explicitly so the public functions can document a single default.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { describeValue } from "./describe-value.ts";
|
|
9
|
+
import { utcDateFromParts } from "./date-only.ts";
|
|
10
|
+
|
|
11
|
+
/** Wall-clock fields an instant shows in a zone, plus the era token for range checks. */
|
|
12
|
+
export interface WallParts {
|
|
13
|
+
year: number;
|
|
14
|
+
month: number;
|
|
15
|
+
day: number;
|
|
16
|
+
hour: number;
|
|
17
|
+
minute: number;
|
|
18
|
+
second: number;
|
|
19
|
+
era: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** The date and time fields used to compare two wall clocks. */
|
|
23
|
+
export type WallTime = Pick<WallParts, "year" | "month" | "day" | "hour" | "minute" | "second">;
|
|
24
|
+
|
|
25
|
+
// Locale, numbering system and calendar are pinned so the parts are ASCII numbers of the
|
|
26
|
+
// proleptic Gregorian calendar whatever the runtime locale is. ICU's Gregorian calendar matches
|
|
27
|
+
// ISO 8601 for years 0001-9999, and the era part is what lets dateOnlyOf reject BCE instants.
|
|
28
|
+
const WALL_FORMAT_OPTIONS: Intl.DateTimeFormatOptions = {
|
|
29
|
+
year: "numeric",
|
|
30
|
+
month: "2-digit",
|
|
31
|
+
day: "2-digit",
|
|
32
|
+
hour: "2-digit",
|
|
33
|
+
minute: "2-digit",
|
|
34
|
+
second: "2-digit",
|
|
35
|
+
hourCycle: "h23",
|
|
36
|
+
calendar: "gregory",
|
|
37
|
+
numberingSystem: "latn",
|
|
38
|
+
era: "short",
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
// Formatter construction dominates Intl formatting cost and an app uses one or two zones; the
|
|
42
|
+
// cap keeps caller-supplied values from growing the cache without bound.
|
|
43
|
+
const MAX_CACHED_FORMATTERS = 64;
|
|
44
|
+
const WALL_FORMATTERS = new Map<string, Intl.DateTimeFormat>();
|
|
45
|
+
|
|
46
|
+
function wallFormatterFor(timeZone: string | undefined): Intl.DateTimeFormat {
|
|
47
|
+
const key = timeZone ?? "";
|
|
48
|
+
let formatter = WALL_FORMATTERS.get(key);
|
|
49
|
+
if (formatter === undefined) {
|
|
50
|
+
if (WALL_FORMATTERS.size >= MAX_CACHED_FORMATTERS) WALL_FORMATTERS.clear();
|
|
51
|
+
formatter = new Intl.DateTimeFormat("en-US", {
|
|
52
|
+
...WALL_FORMAT_OPTIONS,
|
|
53
|
+
...(timeZone === undefined ? {} : { timeZone }),
|
|
54
|
+
});
|
|
55
|
+
WALL_FORMATTERS.set(key, formatter);
|
|
56
|
+
}
|
|
57
|
+
return formatter;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Rejects non-string zones up front; a syntactically invalid zone throws RangeError from Intl. */
|
|
61
|
+
export function assertTimeZone(timeZone: unknown): asserts timeZone is string {
|
|
62
|
+
if (typeof timeZone !== "string") {
|
|
63
|
+
throw new TypeError(
|
|
64
|
+
"@facilis.dev/time: expected a time zone string, received " + describeValue(timeZone),
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Like assertTimeZone, but the omitted runtime-zone default is allowed. */
|
|
70
|
+
export function assertOptionalTimeZone(timeZone: unknown): asserts timeZone is string | undefined {
|
|
71
|
+
if (timeZone !== undefined && typeof timeZone !== "string") {
|
|
72
|
+
throw new TypeError(
|
|
73
|
+
"@facilis.dev/time: expected a time zone string, received " + describeValue(timeZone),
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The wall-clock fields an instant shows in a zone (defaults to the runtime zone). */
|
|
79
|
+
export function wallPartsAt(instantMs: number, timeZone: string | undefined): WallParts {
|
|
80
|
+
assertOptionalTimeZone(timeZone);
|
|
81
|
+
const values = new Map<string, string>();
|
|
82
|
+
for (const part of wallFormatterFor(timeZone).formatToParts(new Date(instantMs))) {
|
|
83
|
+
values.set(part.type, part.value);
|
|
84
|
+
}
|
|
85
|
+
return {
|
|
86
|
+
year: readNumberPart(values, "year"),
|
|
87
|
+
month: readNumberPart(values, "month"),
|
|
88
|
+
day: readNumberPart(values, "day"),
|
|
89
|
+
hour: readNumberPart(values, "hour"),
|
|
90
|
+
minute: readNumberPart(values, "minute"),
|
|
91
|
+
second: readNumberPart(values, "second"),
|
|
92
|
+
era: readTextPart(values, "era"),
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Offset of the zone at an instant, in milliseconds (local wall time minus UTC). */
|
|
97
|
+
export function zoneOffsetMs(instantMs: number, timeZone: string | undefined): number {
|
|
98
|
+
// Whole seconds keep the subtraction exact; UTC offsets never carry a fraction of a second.
|
|
99
|
+
const floored = Math.floor(instantMs / 1000) * 1000;
|
|
100
|
+
return utcDateFromParts(wallPartsAt(floored, timeZone)).getTime() - floored;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Whether two wall clocks name the same local date and time (the era is metadata, not time). */
|
|
104
|
+
export function isSameWallTime(left: WallTime, right: WallTime): boolean {
|
|
105
|
+
return (
|
|
106
|
+
left.year === right.year &&
|
|
107
|
+
left.month === right.month &&
|
|
108
|
+
left.day === right.day &&
|
|
109
|
+
left.hour === right.hour &&
|
|
110
|
+
left.minute === right.minute &&
|
|
111
|
+
left.second === right.second
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function readNumberPart(values: Map<string, string>, type: string): number {
|
|
116
|
+
return Number(readTextPart(values, type));
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function readTextPart(values: Map<string, string>, type: string): string {
|
|
120
|
+
const value = values.get(type);
|
|
121
|
+
if (value === undefined) {
|
|
122
|
+
// WALL_FORMAT_OPTIONS fixes the part set, so a missing part is an Intl contract violation.
|
|
123
|
+
throw new Error('@facilis.dev/time: Intl.DateTimeFormat did not return the "' + type + '" part');
|
|
124
|
+
}
|
|
125
|
+
return value;
|
|
126
|
+
}
|