tiny-ja-date 0.2.0 → 0.3.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/README.md CHANGED
@@ -38,7 +38,7 @@ nextBusinessDay(new Date(2026, 4, 15))
38
38
 
39
39
  ## API
40
40
 
41
- ### `formatJaDate(date: Date | string | number): string`
41
+ ### `formatJaDate(date: DateInput, options?: DateOptions): string`
42
42
 
43
43
  Formats a date as a Japanese date label.
44
44
 
@@ -47,7 +47,7 @@ formatJaDate(new Date(2026, 4, 12))
47
47
  // "2026年5月12日(火)"
48
48
  ```
49
49
 
50
- ### `formatRelativeJaDate(date: Date | string | number, baseDate?: Date | string | number): string`
50
+ ### `formatRelativeJaDate(date: DateInput, baseDate?: DateInput, options?: DateOptions): string`
51
51
 
52
52
  Formats a date relative to a base date.
53
53
 
@@ -68,7 +68,7 @@ formatRelativeJaDate(new Date(2026, 4, 15), new Date(2026, 4, 12))
68
68
  // "3日後"
69
69
  ```
70
70
 
71
- ### `isWeekendJP(date: Date | string | number): boolean`
71
+ ### `isWeekendJP(date: DateInput, options?: DateOptions): boolean`
72
72
 
73
73
  Checks whether the date is Saturday or Sunday.
74
74
 
@@ -79,7 +79,9 @@ isWeekendJP(new Date(2026, 4, 16))
79
79
 
80
80
  ### `nextBusinessDay(date: DateInput, options?: BusinessDayOptions): Date`
81
81
 
82
- Returns the start of the next business day in the runtime's local time zone.
82
+ Returns a `Date` for the start of the next business day in the selected time
83
+ zone. If midnight is skipped, the result is the first valid time on that date.
84
+ If a time zone skipped an entire date, the search continues to the following date.
83
85
 
84
86
  The search starts the day after the input and skips Saturdays, Sundays, and
85
87
  any local calendar dates supplied in `options.holidays`. Each holiday accepts
@@ -93,15 +95,37 @@ nextBusinessDay("2026-05-15", { holidays: ["2026-05-18"] })
93
95
  // Date for 2026-05-19
94
96
  ```
95
97
 
98
+ ## Time zones
99
+
100
+ All four functions accept an optional `timeZone` such as `"Asia/Tokyo"`.
101
+ When omitted, they keep the runtime-local behavior of 0.2. The runtime's
102
+ `Intl.DateTimeFormat` supplies the time zone rules. Unrecognized IANA names
103
+ throw a `RangeError`.
104
+
105
+ ```ts
106
+ const tokyo = { timeZone: "Asia/Tokyo" }
107
+
108
+ formatJaDate("2026-11-23T15:30:00Z", tokyo)
109
+ // "2026年11月24日(火)"
110
+
111
+ formatRelativeJaDate("2026-11-24", undefined, tokyo)
112
+ // Relative to today's date in Tokyo
113
+
114
+ nextBusinessDay("2026-11-20", { ...tokyo, holidays: ["2026-11-23"] }).toISOString()
115
+ // "2026-11-23T15:00:00.000Z" (2026-11-24 at 00:00 in Tokyo)
116
+ ```
117
+
96
118
  ## Date inputs
97
119
 
98
- - `YYYY-MM-DD` strings represent local calendar dates in the runtime's time zone.
120
+ - `YYYY-MM-DD` strings represent calendar dates as written in the selected time
121
+ zone. The runtime-local zone is used when no zone is specified.
99
122
  Invalid dates such as `2026-02-30` throw a `TypeError`.
100
123
  - `Date` objects and Unix timestamps in milliseconds represent instants. The
101
- functions use the instant's date in the runtime's local time zone.
124
+ functions use the instant's date in the selected time zone.
102
125
  - For strings with a time, use ISO 8601 with an explicit offset such as
103
- `2026-05-12T09:00:00+09:00` to identify an instant. Strings without an
104
- explicit offset and other string formats follow JavaScript's `Date` parsing.
126
+ `2026-05-12T09:00:00+09:00` to identify an instant. With an explicit
127
+ `timeZone`, date-time strings without an offset and other string formats
128
+ throw a `TypeError`. Without `timeZone`, they follow JavaScript's `Date` parsing.
105
129
 
106
130
  ### Upgrading from 0.1
107
131
 
@@ -116,7 +140,6 @@ as `2026-05-12T00:00:00Z` to retain the 0.1 interpretation.
116
140
  It does not:
117
141
 
118
142
  - include Japanese holiday data
119
- - convert time zones
120
143
  - format wareki
121
144
  - generate calendars
122
145
  - replace date-fns or dayjs
package/dist/index.d.ts CHANGED
@@ -1,8 +1,11 @@
1
1
  export type DateInput = Date | string | number;
2
- export interface BusinessDayOptions {
2
+ export interface DateOptions {
3
+ timeZone?: string;
4
+ }
5
+ export interface BusinessDayOptions extends DateOptions {
3
6
  holidays?: readonly DateInput[];
4
7
  }
5
- export declare function formatJaDate(input: DateInput): string;
6
- export declare function formatRelativeJaDate(input: DateInput, baseInput?: DateInput): string;
7
- export declare function isWeekendJP(input: DateInput): boolean;
8
+ export declare function formatJaDate(input: DateInput, options?: DateOptions): string;
9
+ export declare function formatRelativeJaDate(input: DateInput, baseInput?: DateInput, options?: DateOptions): string;
10
+ export declare function isWeekendJP(input: DateInput, options?: DateOptions): boolean;
8
11
  export declare function nextBusinessDay(input: DateInput, options?: BusinessDayOptions): Date;
package/dist/index.js CHANGED
@@ -1,7 +1,11 @@
1
1
  const WEEKDAYS_JA = ["日", "月", "火", "水", "木", "金", "土"];
2
2
  const ONE_DAY_MS = 86400000;
3
+ const MAX_DATE_MS = 8640000000000000;
4
+ const GREGORIAN_CYCLE_MS = 146097 * ONE_DAY_MS;
5
+ const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/;
6
+ const OFFSET_DATE_TIME = /^((?:\d{4}|[+-]\d{6}))-(\d{2})-(\d{2})T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})$/i;
3
7
  function toValidDate(input) {
4
- if (typeof input === "string" && /^\d{4}-\d{2}-\d{2}$/.test(input)) {
8
+ if (typeof input === "string" && DATE_ONLY.test(input)) {
5
9
  const [year, month, day] = input.split("-").map(Number);
6
10
  const date = new Date(0);
7
11
  date.setHours(0, 0, 0, 0);
@@ -19,23 +23,132 @@ function toValidDate(input) {
19
23
  }
20
24
  return date;
21
25
  }
22
- function localDayNumber(date) {
23
- const utcDay = new Date(0);
24
- utcDay.setUTCFullYear(date.getFullYear(), date.getMonth(), date.getDate());
25
- return utcDay.getTime() / ONE_DAY_MS;
26
- }
27
- export function formatJaDate(input) {
28
- const date = toValidDate(input);
29
- const year = date.getFullYear();
30
- const month = date.getMonth() + 1;
31
- const day = date.getDate();
32
- const weekday = WEEKDAYS_JA[date.getDay()];
26
+ function utcDay(year, month, day) {
27
+ const date = new Date(0);
28
+ // A zone can project an instant near the Date limit into an adjacent day.
29
+ const cycles = Math.floor((year - 2000) / 400);
30
+ return date.setUTCFullYear(year - cycles * 400, month - 1, day) + cycles * GREGORIAN_CYCLE_MS;
31
+ }
32
+ function checkedUtcDay(year, month, day) {
33
+ const value = utcDay(year, month, day);
34
+ const date = utcDateParts(value);
35
+ if (date.year !== year || date.month !== month || date.day !== day) {
36
+ throw new TypeError("Invalid date");
37
+ }
38
+ return value;
39
+ }
40
+ function utcDateParts(day) {
41
+ const cycles = Math.floor(day / GREGORIAN_CYCLE_MS);
42
+ const date = new Date(day - cycles * GREGORIAN_CYCLE_MS);
43
+ return {
44
+ year: date.getUTCFullYear() + cycles * 400,
45
+ month: date.getUTCMonth() + 1,
46
+ day: date.getUTCDate(),
47
+ };
48
+ }
49
+ function createFormatter(timeZone) {
50
+ if (timeZone === undefined)
51
+ return undefined;
52
+ if (/^[+-]/.test(timeZone))
53
+ throw new RangeError("Expected an IANA time zone name");
54
+ return new Intl.DateTimeFormat("en-US", {
55
+ timeZone,
56
+ calendar: "gregory",
57
+ numberingSystem: "latn",
58
+ era: "short",
59
+ year: "numeric",
60
+ month: "numeric",
61
+ day: "numeric",
62
+ hour: "numeric",
63
+ minute: "numeric",
64
+ second: "numeric",
65
+ hourCycle: "h23",
66
+ });
67
+ }
68
+ // Express the zoned wall clock on the UTC timeline for offset and day arithmetic.
69
+ function wallTime(instant, formatter) {
70
+ const parts = Object.fromEntries(formatter.formatToParts(new Date(instant))
71
+ .map(({ type, value }) => [type, value]));
72
+ const year = Number(parts.year);
73
+ const day = utcDay(parts.era === "BC" ? 1 - year : year, Number(parts.month), Number(parts.day));
74
+ return day + (Number(parts.hour) * 3600 + Number(parts.minute) * 60 + Number(parts.second)) * 1000;
75
+ }
76
+ function calendarDay(input, formatter) {
77
+ if (!formatter) {
78
+ const date = toValidDate(input);
79
+ return utcDay(date.getFullYear(), date.getMonth() + 1, date.getDate());
80
+ }
81
+ if (typeof input === "string") {
82
+ if (DATE_ONLY.test(input)) {
83
+ const [year, month, day] = input.split("-").map(Number);
84
+ return checkedUtcDay(year, month, day);
85
+ }
86
+ const match = OFFSET_DATE_TIME.exec(input);
87
+ if (!match)
88
+ throw new TypeError("Expected YYYY-MM-DD or an ISO date-time with an offset");
89
+ checkedUtcDay(Number(match[1]), Number(match[2]), Number(match[3]));
90
+ }
91
+ const time = wallTime(toValidDate(input).getTime(), formatter);
92
+ return Math.floor(time / ONE_DAY_MS) * ONE_DAY_MS;
93
+ }
94
+ function zonedDayStart(day, formatter) {
95
+ const first = Math.max(-MAX_DATE_MS, day - ONE_DAY_MS * 2);
96
+ const last = Math.min(MAX_DATE_MS, day + ONE_DAY_MS * 2);
97
+ const offsets = new Set();
98
+ let earliest = Infinity;
99
+ let previous = first;
100
+ let previousWall = wallTime(first, formatter);
101
+ if (previousWall >= day && previousWall < day + ONE_DAY_MS)
102
+ earliest = first;
103
+ // Inspect offsets on both sides of midnight to handle repeated wall times.
104
+ for (let instant = first;; instant = Math.min(instant + ONE_DAY_MS / 4, last)) {
105
+ const wall = wallTime(instant, formatter);
106
+ offsets.add(wall - instant);
107
+ // A forward jump can begin the date after midnight or skip the whole date.
108
+ if (previousWall < day && wall >= day) {
109
+ let before = previous;
110
+ let after = instant;
111
+ while (after - before > 1000) {
112
+ const middle = Math.floor((before + after) / 2000) * 1000;
113
+ if (wallTime(middle, formatter) < day)
114
+ before = middle;
115
+ else
116
+ after = middle;
117
+ }
118
+ if (wallTime(after, formatter) < day + ONE_DAY_MS)
119
+ earliest = Math.min(earliest, after);
120
+ }
121
+ if (instant === last)
122
+ break;
123
+ previous = instant;
124
+ previousWall = wall;
125
+ }
126
+ for (const offset of offsets) {
127
+ const instant = day - offset;
128
+ if (Math.abs(instant) <= MAX_DATE_MS && wallTime(instant, formatter) === day) {
129
+ earliest = Math.min(earliest, instant);
130
+ }
131
+ }
132
+ return Number.isFinite(earliest) ? new Date(earliest) : undefined;
133
+ }
134
+ function weekdayOf(day) {
135
+ const weekday = (day / ONE_DAY_MS + 4) % 7;
136
+ return (weekday + 7) % 7;
137
+ }
138
+ function isWeekend(day) {
139
+ const weekday = weekdayOf(day);
140
+ return weekday === 0 || weekday === 6;
141
+ }
142
+ export function formatJaDate(input, options = {}) {
143
+ const formatter = createFormatter(options.timeZone);
144
+ const date = calendarDay(input, formatter);
145
+ const { year, month, day } = utcDateParts(date);
146
+ const weekday = WEEKDAYS_JA[weekdayOf(date)];
33
147
  return `${year}年${month}月${day}日(${weekday})`;
34
148
  }
35
- export function formatRelativeJaDate(input, baseInput = new Date()) {
36
- const date = toValidDate(input);
37
- const baseDate = toValidDate(baseInput);
38
- const diffDays = localDayNumber(date) - localDayNumber(baseDate);
149
+ export function formatRelativeJaDate(input, baseInput = new Date(), options = {}) {
150
+ const formatter = createFormatter(options.timeZone);
151
+ const diffDays = (calendarDay(input, formatter) - calendarDay(baseInput, formatter)) / ONE_DAY_MS;
39
152
  if (diffDays === 0)
40
153
  return "今日";
41
154
  if (diffDays === -1)
@@ -46,18 +159,29 @@ export function formatRelativeJaDate(input, baseInput = new Date()) {
46
159
  return `${Math.abs(diffDays)}日前`;
47
160
  return `${diffDays}日後`;
48
161
  }
49
- export function isWeekendJP(input) {
50
- const date = toValidDate(input);
51
- const day = date.getDay();
52
- return day === 0 || day === 6;
162
+ export function isWeekendJP(input, options = {}) {
163
+ return isWeekend(calendarDay(input, createFormatter(options.timeZone)));
53
164
  }
54
165
  export function nextBusinessDay(input, options = {}) {
55
- const date = toValidDate(input);
56
- const holidays = new Set(options.holidays?.map((holiday) => localDayNumber(toValidDate(holiday))));
57
- date.setHours(0, 0, 0, 0);
58
- do {
59
- date.setDate(date.getDate() + 1);
60
- date.setHours(0, 0, 0, 0);
61
- } while (isWeekendJP(date) || holidays.has(localDayNumber(date)));
62
- return date;
166
+ const formatter = createFormatter(options.timeZone);
167
+ const day = calendarDay(input, formatter);
168
+ const holidays = new Set(options.holidays?.map((holiday) => calendarDay(holiday, formatter)));
169
+ for (let candidate = day + ONE_DAY_MS; candidate <= MAX_DATE_MS + ONE_DAY_MS; candidate += ONE_DAY_MS) {
170
+ if (isWeekend(candidate) || holidays.has(candidate))
171
+ continue;
172
+ if (formatter) {
173
+ const start = zonedDayStart(candidate, formatter);
174
+ if (start)
175
+ return start;
176
+ }
177
+ else {
178
+ const { year, month, day } = utcDateParts(candidate);
179
+ const local = new Date(0);
180
+ local.setHours(0, 0, 0, 0);
181
+ local.setFullYear(year, month - 1, day);
182
+ if (local.getDate() === day)
183
+ return local;
184
+ }
185
+ }
186
+ throw new TypeError("Invalid date");
63
187
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tiny-ja-date",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Tiny TypeScript date utilities for Japanese UI.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -26,6 +26,7 @@
26
26
  "datetime",
27
27
  "format",
28
28
  "relative-date",
29
+ "time-zone",
29
30
  "business-day",
30
31
  "typescript"
31
32
  ],