Landed
Start oscabriel/datekit
Landed as 6a2b761
authored by oscabriel · committed by the platform · the first commit · Browse files · 21 files·+1112 added−0 removed
21 files changed+1112 added−0 removed
added:.myr/project.ts+23 added
1234567891011121314151617181920212223import { kinds, project } from "@myr/cli/rules";
/** * How datekit takes changes. Each change we want is an ask in asks/, with a * test that fails on main; an answer lands when that test passes and the * rest of the suite stays green. ines-v decides for the whole library, and * okonkwo for time zones. */export default project({ agents: "trailer", deciders: { "**": ["ines-v"], "src/tz.ts": ["okonkwo"], }, kinds: [kinds.fix, kinds.changeJudge], run: { // An open ask's test fails on main until it is answered, so the suite // every answer must keep green leaves the asks' tests to their own lane. checks: { unit: "bun test --path-ignore-patterns='test/asks/**'" }, test: "bun test {path}", }, vouch: "forCode",});added:.myr/visibility.ts+26 added
1234567891011121314151617181920212223242526import { flows, layer, sealedChecks, visibility } from "@myr/cli/rules";
/** * What datekit keeps out of its public tree, and why. The maintainers hold * checks for how dates are shown (export) and read (parser) in a layer of * their own, beside their review rubric. Every answer is judged by those * checks too, and learns only which area failed. Everything else is open. */export default visibility({ checks: sealedChecks({ // A new check joins only after it passes main three times and fails on // at least one known-bad tree. admit: { greenOnMainRuns: 3, redOnKnownBadAtLeast: 1 }, areas: { export: "src/format.ts", parser: "src/parse.ts" }, canary: true, }), flows: flows.noWriteDown(), layers: { maintainers: layer({ disclose: "sealed", holds: ["checks", "notes"], reason: "Held-back checks for export and parser, and the maintainers' review rubric", }), }, notice: { narrowing: "7 days" },});added:.myr/vouched.td+11 added
1+# The people vouched for in datekit, and anyone denounced.2+#3+# A vouch lets a person claim an ask and offer a sealed answer; anyone not4+# denounced may propose an ask. A maintainer adds a line by landing it.5+#6+# One handle per line, without @, in alphabetical order. A `platform:`7+# prefix names a handle somewhere else, a leading minus denounces, and8+# whatever follows the handle after a space is a note.9+bram first answer landed in 0.4.010+ines-v maintainer11+okonkwo maintainer, time zonesadded:src/add.ts+39 added
123456789101112131415161718192021222324252627282930313233343536373839/** * Moving a date by whole units. Each function returns a new date and leaves * its argument alone. Amounts are whole numbers: a fraction is dropped * toward zero (`addDays(date, 1.9)` adds one day). An invalid date stays * invalid. */import { MS_PER_DAY, MS_PER_HOUR, MS_PER_MINUTE, MS_PER_SECOND } from "./calendar.ts";
const by = (date: Date, amount: number, unit: number): Date => new Date(date.getTime() + Math.trunc(amount) * unit);
export const addMilliseconds = (date: Date, amount: number): Date => by(date, amount, 1);
export const addSeconds = (date: Date, amount: number): Date => by(date, amount, MS_PER_SECOND);
export const addMinutes = (date: Date, amount: number): Date => by(date, amount, MS_PER_MINUTE);
export const addHours = (date: Date, amount: number): Date => by(date, amount, MS_PER_HOUR);
/** Adds days. datekit works in UTC, where every day is 24 hours long. */export const addDays = (date: Date, amount: number): Date => by(date, amount, MS_PER_DAY);
export const addWeeks = (date: Date, amount: number): Date => addDays(date, Math.trunc(amount) * 7);
/** * Adds calendar months, keeping the day of the month and the time of day: * October 7 plus three months is January 7. */export const addMonths = (date: Date, amount: number): Date => { const next = new Date(date.getTime());
next.setUTCMonth(next.getUTCMonth() + Math.trunc(amount));
return next;};
/** Adds calendar years: twelve months each. */export const addYears = (date: Date, amount: number): Date => addMonths(date, Math.trunc(amount) * 12);added:src/calendar.ts+38 added
1234567891011121314151617181920212223242526272829303132333435363738/** * The proleptic Gregorian calendar, in UTC: leap years, month lengths, and * the instant a calendar day starts. Months are 1 to 12 here, as people * write them, not 0 to 11 as `Date` counts them. */
export const MS_PER_SECOND = 1000;export const MS_PER_MINUTE = 60 * MS_PER_SECOND;export const MS_PER_HOUR = 60 * MS_PER_MINUTE;export const MS_PER_DAY = 24 * MS_PER_HOUR;
/** Whether `year` has a February 29. */export const isLeapYear = (year: number): boolean => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
const MONTH_LENGTHS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
/** How many days `month` (1 to 12) of `year` has. */export const daysInMonth = (year: number, month: number): number => month === 2 && isLeapYear(year) ? 29 : (MONTH_LENGTHS[month - 1] ?? Number.NaN);
/** How many days `year` has: 365, or 366 in a leap year. */export const daysInYear = (year: number): number => (isLeapYear(year) ? 366 : 365);
/** * The instant `year-month-day` starts in UTC, in epoch milliseconds. * `Date.UTC` reads the years 0 to 99 as 1900 to 1999; this doesn't. */export const utcMidnight = (year: number, month: number, day: number): number => { const date = new Date(0);
date.setUTCFullYear(year, month - 1, day);
return date.getTime();};
/** The ISO weekday of an instant in UTC: Monday is 1 and Sunday is 7. */export const isoWeekday = (date: Date): number => date.getUTCDay() || 7;added:src/diff.ts+45 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445/** * How far apart two dates are. Each function takes the later date first and * counts whole units, dropping a part unit toward zero, so the answer is * negative when the first date is the earlier one. An invalid date gives * `NaN`. */import { MS_PER_DAY, MS_PER_HOUR, MS_PER_MINUTE, MS_PER_SECOND, utcMidnight } from "./calendar.ts";
// `+ 0` turns the `-0` that `Math.trunc(-0.5)` gives into `0`.const wholeUnits = (later: Date, earlier: Date, unit: number): number => Math.trunc((later.getTime() - earlier.getTime()) / unit) + 0;
export const diffInMilliseconds = (later: Date, earlier: Date): number => later.getTime() - earlier.getTime();
export const diffInSeconds = (later: Date, earlier: Date): number => wholeUnits(later, earlier, MS_PER_SECOND);
export const diffInMinutes = (later: Date, earlier: Date): number => wholeUnits(later, earlier, MS_PER_MINUTE);
export const diffInHours = (later: Date, earlier: Date): number => wholeUnits(later, earlier, MS_PER_HOUR);
/** * Whole 24-hour days between two instants: from 12:00 one day to 11:00 the * next is 0 days. To count the midnights crossed, use `diffInCalendarDays`. */export const diffInDays = (later: Date, earlier: Date): number => wholeUnits(later, earlier, MS_PER_DAY);
export const diffInWeeks = (later: Date, earlier: Date): number => wholeUnits(later, earlier, 7 * MS_PER_DAY);
const startOfUtcDay = (date: Date) => utcMidnight(date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate());
/** The UTC midnights between two dates: from 23:59 one day to 00:00 the next is 1. */export const diffInCalendarDays = (later: Date, earlier: Date): number => Math.round((startOfUtcDay(later) - startOfUtcDay(earlier)) / MS_PER_DAY) + 0;
/** The month boundaries between two dates: from October 31 to January 1 is 3. */export const diffInCalendarMonths = (later: Date, earlier: Date): number => (later.getUTCFullYear() - earlier.getUTCFullYear()) * 12 + (later.getUTCMonth() - earlier.getUTCMonth());added:src/format.ts+134 added
1+/**2+ * Showing a date as text with a pattern: `format(date, "d MMMM yyyy")` is3+ * `7 October 2026`. Letters are tokens; text in single quotes is printed as4+ * it is (`''` prints one quote); any other character passes through. A5+ * letter that is no token is refused, so a typo never prints a wrong date.6+ */7+import { isValid } from "./parse.ts";8+import { utcParts, zonedParts } from "./tz.ts";9+import type { ZonedParts } from "./tz.ts";10+11+/** How `format` shows a date. */12+export interface FormatOptions {13+ /** The IANA zone to show the date in (`America/New_York`); UTC when left out. */14+ readonly timeZone?: string;15+}16+17+const MONTHS = [18+ "January",19+ "February",20+ "March",21+ "April",22+ "May",23+ "June",24+ "July",25+ "August",26+ "September",27+ "October",28+ "November",29+ "December",30+];31+32+const WEEKDAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];33+34+const pad = (value: number, width: number) => String(value).padStart(width, "0");35+36+// The English suffix by last digit: 1st, 2nd, 3rd, and th for the rest.37+const SUFFIXES = ["th", "st", "nd", "rd"];38+39+/** A number as an English ordinal: `1st`, `2nd`, `3rd`, `4th`. */40+export const ordinal = (value: number): string => `${value}${SUFFIXES[value % 10] ?? "th"}`;41+42+/** A UTC offset as `Z`, or `+09:00`, `-04:00`, `+05:30`. */43+const offsetText = (minutes: number) => {44+ if (minutes === 0) {45+ return "Z";46+ }47+48+ const sign = minutes < 0 ? "-" : "+";49+ const size = Math.abs(minutes);50+51+ return `${sign}${pad(Math.floor(size / 60), 2)}:${pad(size % 60, 2)}`;52+};53+54+const twelveHour = (hour: number) => hour % 12 || 12;55+56+/** Each token, and how it shows a date's fields. */57+const TOKENS: Readonly<Record<string, (parts: ZonedParts) => string>> = {58+ // Year59+ yyyy: ({ year }) => pad(year, 4),60+ yy: ({ year }) => pad(year % 100, 2),61+ // Month62+ MMMM: ({ month }) => MONTHS[month - 1] ?? "",63+ MMM: ({ month }) => (MONTHS[month - 1] ?? "").slice(0, 3),64+ MM: ({ month }) => pad(month, 2),65+ M: ({ month }) => String(month),66+ // Day of the month67+ Do: ({ day }) => ordinal(day),68+ dd: ({ day }) => pad(day, 2),69+ d: ({ day }) => String(day),70+ // Day of the week71+ EEEE: ({ weekday }) => WEEKDAYS[weekday - 1] ?? "",72+ EEE: ({ weekday }) => (WEEKDAYS[weekday - 1] ?? "").slice(0, 3),73+ // Time74+ HH: ({ hour }) => pad(hour, 2),75+ H: ({ hour }) => String(hour),76+ hh: ({ hour }) => pad(twelveHour(hour), 2),77+ h: ({ hour }) => String(twelveHour(hour)),78+ a: ({ hour }) => (hour < 12 ? "AM" : "PM"),79+ mm: ({ minute }) => pad(minute, 2),80+ ss: ({ second }) => pad(second, 2),81+ SSS: ({ millisecond }) => pad(millisecond, 3),82+ // Offset83+ XXX: ({ offset }) => offsetText(offset),84+};85+86+// A quoted literal (to its closing quote, or the end), `Do`, a run of one87+// letter, or anything that isn't a letter or a quote.88+const PIECES = /'(?:[^']|'')*(?:'|$)|Do|([A-Za-z])\1*|[^A-Za-z']+/gu;89+90+/** One piece of a pattern, shown. */91+const show = (piece: string, parts: ZonedParts): string => {92+ if (piece.startsWith("'")) {93+ return piece === "''"94+ ? "'"95+ : piece.slice(1, piece.endsWith("'") ? -1 : undefined).replaceAll("''", "'");96+ }97+98+ if (!/^[A-Za-z]/u.test(piece)) {99+ return piece;100+ }101+102+ const token = TOKENS[piece];103+104+ if (token === undefined) {105+ throw new RangeError(`format: "${piece}" is not a token; quote literal text, like 'at'`);106+ }107+108+ return token(parts);109+};110+111+/**112+ * Shows `date` with `pattern`, in UTC or in `options.timeZone`. Throws a113+ * `RangeError` for an invalid date, an unknown token or an unknown zone.114+ *115+ * | Token | Shows | Example |116+ * | --- | --- | --- |117+ * | `yyyy`, `yy` | year | `2026`, `26` |118+ * | `MMMM`, `MMM`, `MM`, `M` | month | `October`, `Oct`, `10`, `10` |119+ * | `Do`, `dd`, `d` | day of the month | `7th`, `07`, `7` |120+ * | `EEEE`, `EEE` | day of the week | `Wednesday`, `Wed` |121+ * | `HH`, `H`, `hh`, `h`, `a` | hour, 24- and 12-hour, and AM or PM | `14`, `14`, `02`, `2`, `PM` |122+ * | `mm`, `ss`, `SSS` | minute, second, millisecond | `05`, `09`, `250` |123+ * | `XXX` | UTC offset | `Z`, `+09:00` |124+ */125+export const format = (date: Date, pattern: string, options: FormatOptions = {}): string => {126+ if (!isValid(date)) {127+ throw new RangeError("format: the date is invalid");128+ }129+130+ const parts =131+ options.timeZone === undefined ? utcParts(date) : zonedParts(date, options.timeZone);132+133+ return (pattern.match(PIECES) ?? []).map((piece) => show(piece, parts)).join("");134+};added:src/index.ts+28 added
12345678910111213141516171819202122232425262728/** * datekit: small, dependency-free date helpers. Dates are plain `Date` * instants; datekit reads and shows them in UTC unless you name a time zone. */export { addDays, addHours, addMilliseconds, addMinutes, addMonths, addSeconds, addWeeks, addYears,} from "./add.ts";export { daysInMonth, daysInYear, isLeapYear } from "./calendar.ts";export { diffInCalendarDays, diffInCalendarMonths, diffInDays, diffInHours, diffInMilliseconds, diffInMinutes, diffInSeconds, diffInWeeks,} from "./diff.ts";export { format, ordinal, type FormatOptions } from "./format.ts";export { invalidDate, isValid, parseISO } from "./parse.ts";export { isTimeZone, offsetIn, type ZonedParts, zonedParts } from "./tz.ts";added:src/parse.ts+140 added
1+/**2+ * Reading ISO 8601 text. `parseISO` reads calendar dates and ordinal dates,3+ * with an optional time and UTC offset, and never throws: text it can't read4+ * gives an invalid date, which `isValid` tells apart.5+ */6+import {7+ MS_PER_HOUR,8+ MS_PER_MINUTE,9+ MS_PER_SECOND,10+ daysInMonth,11+ daysInYear,12+ utcMidnight,13+} from "./calendar.ts";14+15+/** A date that stands for no instant: what `parseISO` gives for text it can't read. */16+export const invalidDate = (): Date => new Date(Number.NaN);17+18+/** Whether `date` stands for an instant (an invalid date doesn't). */19+export const isValid = (date: Date): boolean => !Number.isNaN(date.getTime());20+21+/** The date forms `parseISO` reads, extended and basic. */22+const CALENDAR_DATES = [23+ /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/u,24+ /^(?<year>\d{4})(?<month>\d{2})(?<day>\d{2})$/u,25+ /^(?<year>\d{4})-(?<month>\d{2})$/u,26+ /^(?<year>\d{4})$/u,27+];28+29+const ORDINAL_DATE = /^(?<year>\d{4})-?(?<ordinal>\d{3})$/u;30+31+const TIME =32+ /^(?<hour>\d{2})(?::(?<minute>\d{2})(?::(?<second>\d{2})(?:[.,](?<fraction>\d{1,9}))?)?)?(?<offset>Z|[+-]\d{2}(?::?\d{2})?)?$/u;33+34+const OFFSET = /^(?<sign>[+-])(?<hours>\d{2}):?(?<minutes>\d{2})?$/u;35+36+const whole = (digits: string | undefined, fallback = 0): number =>37+ digits === undefined ? fallback : Number(digits);38+39+/** A calendar date, as the instant it starts in UTC; `undefined` when it isn't a real day. */40+const calendarDay = (year: number, month: number, day: number): number | undefined =>41+ month >= 1 && month <= 12 && day >= 1 && day <= daysInMonth(year, month)42+ ? utcMidnight(year, month, day)43+ : undefined;44+45+/** The start of the day the date part names, in epoch milliseconds. */46+const readDate = (text: string): number | undefined => {47+ for (const form of CALENDAR_DATES) {48+ const groups = form.exec(text)?.groups;49+50+ if (groups !== undefined) {51+ return calendarDay(whole(groups.year), whole(groups.month, 1), whole(groups.day, 1));52+ }53+ }54+55+ const ordinal = ORDINAL_DATE.exec(text)?.groups;56+57+ if (ordinal !== undefined) {58+ const year = whole(ordinal.year);59+ const day = whole(ordinal.ordinal);60+61+ return day >= 1 && day <= daysInYear(year) ? utcMidnight(year, 1, day) : undefined;62+ }63+64+ return undefined;65+};66+67+/** A UTC offset (`Z`, `+09:00`, `-0330`, `+05`) in minutes east of UTC. */68+const readOffset = (text: string | undefined): number | undefined => {69+ if (text === undefined || text === "Z") {70+ return 0;71+ }72+73+ const groups = OFFSET.exec(text)?.groups;74+75+ if (groups === undefined) {76+ return undefined;77+ }78+79+ const hours = whole(groups.hours);80+ const minutes = whole(groups.minutes);81+82+ if (hours > 23 || minutes > 59) {83+ return undefined;84+ }85+86+ return (groups.sign === "-" ? -1 : 1) * (hours * 60 + minutes);87+};88+89+/** How far past midnight the time part is, in UTC milliseconds (its offset taken off). */90+const readTime = (text: string): number | undefined => {91+ const groups = TIME.exec(text)?.groups;92+93+ if (groups === undefined) {94+ return undefined;95+ }96+97+ const hour = whole(groups.hour);98+ const minute = whole(groups.minute);99+ const second = whole(groups.second);100+ const offset = readOffset(groups.offset);101+102+ if (hour > 23 || minute > 59 || second > 59 || offset === undefined) {103+ return undefined;104+ }105+106+ // Digits past the millisecond are dropped, not rounded.107+ const millisecond = whole((groups.fraction ?? "").padEnd(3, "0").slice(0, 3));108+109+ return (110+ hour * MS_PER_HOUR +111+ minute * MS_PER_MINUTE +112+ second * MS_PER_SECOND +113+ millisecond -114+ offset * MS_PER_MINUTE115+ );116+};117+118+/**119+ * Reads ISO 8601 text: a date (`2026-10-07`, `20261007`, `2026-10`, `2026`,120+ * or the ordinal `2026-280`), then optionally `T` and a time (`14:30`,121+ * `14:30:15`, `14:30:15.250`) with a UTC offset (`Z`, `+09:00`). Text with122+ * no offset is read as UTC. Anything else, or a day that doesn't exist123+ * (`2026-02-29`), gives an invalid date.124+ */125+export const parseISO = (text: string): Date => {126+ const [datePart = "", timePart, ...rest] = text.trim().split("T");127+ const day = readDate(datePart);128+129+ if (day === undefined || rest.length > 0) {130+ return invalidDate();131+ }132+133+ if (timePart === undefined) {134+ return new Date(day);135+ }136+137+ const time = readTime(timePart);138+139+ return time === undefined ? invalidDate() : new Date(day + time);140+};added:src/tz.ts+98 added
1+/**2+ * Time zones. datekit keeps every date as an instant and works in UTC; a3+ * time zone matters only when a date is shown, so this module turns an4+ * instant into the wall-clock fields of an IANA zone (`Europe/Lisbon`), with5+ * the zone's offset at that instant. The zone data is the runtime's own6+ * (`Intl`), so datekit ships none.7+ */8+import { MS_PER_MINUTE, isoWeekday, utcMidnight } from "./calendar.ts";9+10+/** An instant's wall-clock fields in one zone, and the zone's offset from UTC then. */11+export interface ZonedParts {12+ readonly year: number;13+ /** 1 to 12. */14+ readonly month: number;15+ readonly day: number;16+ /** 0 to 23. */17+ readonly hour: number;18+ readonly minute: number;19+ readonly second: number;20+ readonly millisecond: number;21+ /** The ISO weekday: Monday is 1 and Sunday is 7. */22+ readonly weekday: number;23+ /** Minutes east of UTC: `+09:00` is 540. */24+ readonly offset: number;25+}26+27+/** An instant's fields in UTC. */28+export const utcParts = (date: Date): ZonedParts => ({29+ day: date.getUTCDate(),30+ hour: date.getUTCHours(),31+ millisecond: date.getUTCMilliseconds(),32+ minute: date.getUTCMinutes(),33+ month: date.getUTCMonth() + 1,34+ offset: 0,35+ second: date.getUTCSeconds(),36+ weekday: isoWeekday(date),37+ year: date.getUTCFullYear(),38+});39+40+/** Whether the runtime knows `name` as a time zone. */41+export const isTimeZone = (name: string): boolean => {42+ try {43+ new Intl.DateTimeFormat("en-US", { timeZone: name });44+45+ return true;46+ } catch {47+ return false;48+ }49+};50+51+const fieldsIn = (timeZone: string) =>52+ new Intl.DateTimeFormat("en-US", {53+ day: "numeric",54+ hour: "numeric",55+ hourCycle: "h23",56+ minute: "numeric",57+ month: "numeric",58+ second: "numeric",59+ timeZone,60+ year: "numeric",61+ });62+63+/**64+ * An instant's fields in the IANA zone `timeZone`. Throws a `RangeError`65+ * for a zone the runtime doesn't know.66+ */67+export const zonedParts = (date: Date, timeZone: string): ZonedParts => {68+ const parts = new Map(69+ fieldsIn(timeZone)70+ .formatToParts(date)71+ .map(({ type, value }) => [type, Number(value)]),72+ );73+74+ const field = (type: Intl.DateTimeFormatPartTypes) => parts.get(type) ?? 0;75+ const millisecond = date.getUTCMilliseconds();76+ const wall = new Date(utcMidnight(field("year"), field("month"), field("day")));77+78+ // The wall clock read as if it were UTC, less the instant, is the offset.79+ const wallTime =80+ wall.getTime() +81+ ((field("hour") * 60 + field("minute")) * 60 + field("second")) * 1000 +82+ millisecond;83+84+ return {85+ day: field("day"),86+ hour: field("hour"),87+ millisecond,88+ minute: field("minute"),89+ month: field("month"),90+ offset: Math.round((wallTime - date.getTime()) / MS_PER_MINUTE),91+ second: field("second"),92+ weekday: isoWeekday(wall),93+ year: field("year"),94+ };95+};96+97+/** The offset of `timeZone` from UTC at `date`, in minutes east of UTC. */98+export const offsetIn = (date: Date, timeZone: string): number => zonedParts(date, timeZone).offset;added:test/add.test.ts+79 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879import { describe, expect, test } from "bun:test";
import { addDays, addHours, addMilliseconds, addMinutes, addMonths, addSeconds, addWeeks, addYears, isValid,} from "../src/index.ts";
const at = (text: string) => new Date(text);
describe("addDays and addWeeks", () => { test("move across a month and a year, keeping the time of day", () => { expect(addDays(at("2026-10-07T09:30:00Z"), 1).toISOString()).toBe("2026-10-08T09:30:00.000Z"); expect(addDays(at("2026-12-31T09:30:00Z"), 1).toISOString()).toBe("2027-01-01T09:30:00.000Z"); expect(addDays(at("2028-02-28T00:00:00Z"), 1).toISOString()).toBe("2028-02-29T00:00:00.000Z"); expect(addDays(at("2026-03-01T00:00:00Z"), -1).toISOString()).toBe("2026-02-28T00:00:00.000Z"); expect(addWeeks(at("2026-10-07T00:00:00Z"), 2).toISOString()).toBe("2026-10-21T00:00:00.000Z"); });
test("drop a fraction toward zero", () => { expect(addDays(at("2026-10-07T00:00:00Z"), 1.9).toISOString()).toBe("2026-10-08T00:00:00.000Z"); expect(addDays(at("2026-10-07T00:00:00Z"), -1.9).toISOString()).toBe( "2026-10-06T00:00:00.000Z", ); });
test("leave their argument alone", () => { const date = at("2026-10-07T00:00:00Z");
addDays(date, 3);
expect(date.toISOString()).toBe("2026-10-07T00:00:00.000Z"); });});
describe("addHours, addMinutes, addSeconds and addMilliseconds", () => { test("move by exact amounts of time", () => { const date = at("2026-10-07T23:30:00Z");
expect(addHours(date, 1).toISOString()).toBe("2026-10-08T00:30:00.000Z"); expect(addMinutes(date, -45).toISOString()).toBe("2026-10-07T22:45:00.000Z"); expect(addSeconds(date, 90).toISOString()).toBe("2026-10-07T23:31:30.000Z"); expect(addMilliseconds(date, 250).toISOString()).toBe("2026-10-07T23:30:00.250Z"); });});
describe("addMonths and addYears", () => { test("keep the day of the month when the target month has it", () => { expect(addMonths(at("2026-01-15T00:00:00Z"), 1).toISOString()).toBe("2026-02-15T00:00:00.000Z"); expect(addMonths(at("2026-10-07T08:00:00Z"), 3).toISOString()).toBe("2027-01-07T08:00:00.000Z"); expect(addMonths(at("2026-03-15T00:00:00Z"), -2).toISOString()).toBe( "2026-01-15T00:00:00.000Z", ); expect(addMonths(at("2026-10-07T00:00:00Z"), 0).toISOString()).toBe("2026-10-07T00:00:00.000Z"); });
test("add twelve months a year", () => { expect(addYears(at("2026-10-07T00:00:00Z"), 2).toISOString()).toBe("2028-10-07T00:00:00.000Z"); expect(addYears(at("2026-10-07T00:00:00Z"), -26).toISOString()).toBe( "2000-10-07T00:00:00.000Z", ); });});
describe("an invalid date", () => { test("stays invalid", () => { const invalid = new Date(Number.NaN);
expect(isValid(addDays(invalid, 1))).toBe(false); expect(isValid(addMonths(invalid, 1))).toBe(false); expect(isValid(addHours(invalid, 1))).toBe(false); });});added:test/diff.test.ts+73 added
1+import { describe, expect, test } from "bun:test";2+3+import {4+ daysInMonth,5+ diffInCalendarDays,6+ diffInCalendarMonths,7+ diffInDays,8+ diffInHours,9+ diffInMilliseconds,10+ diffInMinutes,11+ diffInSeconds,12+ diffInWeeks,13+ isLeapYear,14+} from "../src/index.ts";15+16+const at = (text: string) => new Date(text);17+18+describe("diffInDays", () => {19+ test("counts whole 24-hour days, toward zero", () => {20+ expect(diffInDays(at("2026-10-08T00:00:00Z"), at("2026-10-07T12:00:00Z"))).toBe(0);21+ expect(diffInDays(at("2026-10-09T01:00:00Z"), at("2026-10-07T00:00:00Z"))).toBe(2);22+ expect(diffInDays(at("2026-10-07T00:00:00Z"), at("2026-10-09T01:00:00Z"))).toBe(-2);23+ expect(diffInDays(at("2026-10-07T00:00:00Z"), at("2026-10-07T12:00:00Z"))).toBe(0);24+ });25+26+ test("counts February 29 in a leap year", () => {27+ expect(diffInDays(at("2028-03-01T00:00:00Z"), at("2028-02-01T00:00:00Z"))).toBe(29);28+ expect(diffInDays(at("2026-03-01T00:00:00Z"), at("2026-02-01T00:00:00Z"))).toBe(28);29+ });30+31+ test("gives NaN for an invalid date", () => {32+ expect(diffInDays(new Date(Number.NaN), at("2026-10-07T00:00:00Z"))).toBeNaN();33+ });34+});35+36+describe("diffInCalendarDays", () => {37+ test("counts the UTC midnights crossed", () => {38+ expect(diffInCalendarDays(at("2026-10-08T00:00:00Z"), at("2026-10-07T23:59:00Z"))).toBe(1);39+ expect(diffInCalendarDays(at("2026-10-07T23:59:00Z"), at("2026-10-07T00:00:00Z"))).toBe(0);40+ expect(diffInCalendarDays(at("2027-01-01T00:00:00Z"), at("2026-01-01T00:00:00Z"))).toBe(365);41+ });42+});43+44+describe("diffInCalendarMonths", () => {45+ test("counts the month boundaries crossed", () => {46+ expect(diffInCalendarMonths(at("2027-01-01T00:00:00Z"), at("2026-10-31T00:00:00Z"))).toBe(3);47+ expect(diffInCalendarMonths(at("2026-10-31T00:00:00Z"), at("2026-10-01T00:00:00Z"))).toBe(0);48+ expect(diffInCalendarMonths(at("2026-01-01T00:00:00Z"), at("2026-10-31T00:00:00Z"))).toBe(-9);49+ });50+});51+52+describe("the smaller units", () => {53+ test("count whole hours, minutes, seconds and weeks", () => {54+ const start = at("2026-10-07T00:00:00Z");55+ const later = at("2026-10-21T01:30:45.500Z");56+57+ expect(diffInMilliseconds(later, start)).toBe(1_215_045_500);58+ expect(diffInSeconds(later, start)).toBe(1_215_045);59+ expect(diffInMinutes(later, start)).toBe(20_250);60+ expect(diffInHours(later, start)).toBe(337);61+ expect(diffInWeeks(later, start)).toBe(2);62+ });63+});64+65+describe("the calendar", () => {66+ test("knows the leap years and the length of each month", () => {67+ expect([1900, 2000, 2026, 2028].map(isLeapYear)).toStrictEqual([false, true, false, true]);68+ expect(daysInMonth(2028, 2)).toBe(29);69+ expect(daysInMonth(2026, 2)).toBe(28);70+ expect(daysInMonth(2026, 4)).toBe(30);71+ expect(daysInMonth(2026, 12)).toBe(31);72+ });73+});added:test/format.test.ts+95 added
1+import { describe, expect, test } from "bun:test";2+3+import { format, isTimeZone, offsetIn } from "../src/index.ts";4+5+// Wednesday, October 7, 2026, 14:05:09.250 UTC.6+const afternoon = new Date(Date.UTC(2026, 9, 7, 14, 5, 9, 250));7+8+const on = (year: number, month: number, day: number, hour = 0, minute = 0) =>9+ new Date(Date.UTC(year, month - 1, day, hour, minute));10+11+describe("format", () => {12+ test("shows the year, month and day by their tokens", () => {13+ expect(format(afternoon, "yyyy-MM-dd")).toBe("2026-10-07");14+ expect(format(afternoon, "d MMMM yyyy")).toBe("7 October 2026");15+ expect(format(afternoon, "EEE, d MMM yy")).toBe("Wed, 7 Oct 26");16+ expect(format(afternoon, "EEEE M/d")).toBe("Wednesday 10/7");17+ });18+19+ test("shows the time on a 24-hour and a 12-hour clock", () => {20+ expect(format(afternoon, "HH:mm:ss.SSS")).toBe("14:05:09.250");21+ expect(format(afternoon, "h:mm a")).toBe("2:05 PM");22+ expect(format(on(2026, 10, 7, 0, 5), "hh:mm a")).toBe("12:05 AM");23+ expect(format(on(2026, 10, 7, 12), "h a")).toBe("12 PM");24+ expect(format(on(2026, 10, 7, 9), "H")).toBe("9");25+ });26+27+ test("shows the day of the month as an English ordinal", () => {28+ const days = [1, 2, 3, 4, 10, 20, 21, 22, 23, 24, 30, 31];29+30+ expect(days.map((day) => format(on(2026, 1, day), "Do"))).toStrictEqual([31+ "1st",32+ "2nd",33+ "3rd",34+ "4th",35+ "10th",36+ "20th",37+ "21st",38+ "22nd",39+ "23rd",40+ "24th",41+ "30th",42+ "31st",43+ ]);44+ });45+46+ test("prints quoted text as it is, and '' as one quote", () => {47+ expect(format(afternoon, "'Week of' MMMM d")).toBe("Week of October 7");48+ expect(format(afternoon, "h 'o''clock'")).toBe("2 o'clock");49+ expect(format(afternoon, "yyyy''MM")).toBe("2026'10");50+ expect(format(afternoon, "'at' HH:mm 'sharp")).toBe("at 14:05 sharp");51+ });52+53+ test("passes punctuation and spaces through", () => {54+ expect(format(afternoon, "[yyyy] (MM) / dd.")).toBe("[2026] (10) / 07.");55+ });56+57+ test("refuses a letter that is no token, an invalid date and an unknown zone", () => {58+ expect(() => format(afternoon, "yyyy-MM-dd at HH")).toThrow(RangeError);59+ expect(() => format(afternoon, "yyy")).toThrow(RangeError);60+ expect(() => format(new Date(Number.NaN), "yyyy")).toThrow(RangeError);61+ expect(() => format(afternoon, "HH", { timeZone: "Mars/Olympus_Mons" })).toThrow(RangeError);62+ });63+64+ test("shows UTC's offset as Z", () => {65+ expect(format(afternoon, "yyyy-MM-dd'T'HH:mm:ssXXX")).toBe("2026-10-07T14:05:09Z");66+ });67+});68+69+describe("format in a time zone", () => {70+ test("shows the wall clock of the zone, with its offset", () => {71+ const zoned = (timeZone: string) => format(afternoon, "yyyy-MM-dd HH:mm XXX EEE", { timeZone });72+73+ expect(zoned("Asia/Tokyo")).toBe("2026-10-07 23:05 +09:00 Wed");74+ expect(zoned("Asia/Kolkata")).toBe("2026-10-07 19:35 +05:30 Wed");75+ expect(zoned("America/Sao_Paulo")).toBe("2026-10-07 11:05 -03:00 Wed");76+ expect(zoned("Pacific/Kiritimati")).toBe("2026-10-08 04:05 +14:00 Thu");77+ expect(zoned("UTC")).toBe("2026-10-07 14:05 Z Wed");78+ });79+80+ test("follows daylight saving time", () => {81+ expect(format(on(2026, 7, 1, 12), "HH:mm XXX", { timeZone: "America/New_York" })).toBe(82+ "08:00 -04:00",83+ );84+ expect(format(on(2026, 1, 15, 12), "HH:mm XXX", { timeZone: "America/New_York" })).toBe(85+ "07:00 -05:00",86+ );87+ expect(offsetIn(on(2026, 7, 1), "Europe/Lisbon")).toBe(60);88+ expect(offsetIn(on(2026, 12, 1), "Europe/Lisbon")).toBe(0);89+ });90+91+ test("knows the zones the runtime knows", () => {92+ expect(isTimeZone("Europe/Lisbon")).toBe(true);93+ expect(isTimeZone("Mars/Olympus_Mons")).toBe(false);94+ });95+});added:test/parse.test.ts+78 added
1+import { describe, expect, test } from "bun:test";2+3+import { isValid, parseISO } from "../src/index.ts";4+5+const iso = (text: string) => parseISO(text).toISOString();6+7+describe("parseISO", () => {8+ test("reads a calendar date as the UTC midnight it starts at", () => {9+ expect(iso("2026-10-07")).toBe("2026-10-07T00:00:00.000Z");10+ expect(iso("20261007")).toBe("2026-10-07T00:00:00.000Z");11+ });12+13+ test("reads a year and month as the month's first day, and a year as January 1", () => {14+ expect(iso("2026-10")).toBe("2026-10-01T00:00:00.000Z");15+ expect(iso("2026")).toBe("2026-01-01T00:00:00.000Z");16+ });17+18+ test("reads an ordinal date as the nth day of the year", () => {19+ expect(iso("2026-280")).toBe("2026-10-07T00:00:00.000Z");20+ expect(iso("2026280")).toBe("2026-10-07T00:00:00.000Z");21+ expect(iso("2028-366")).toBe("2028-12-31T00:00:00.000Z");22+ });23+24+ test("reads a time with no offset as UTC", () => {25+ expect(iso("2026-10-07T14:30")).toBe("2026-10-07T14:30:00.000Z");26+ expect(iso("2026-10-07T14")).toBe("2026-10-07T14:00:00.000Z");27+ expect(iso("2026-10-07T14:30:15.250")).toBe("2026-10-07T14:30:15.250Z");28+ });29+30+ test("takes a UTC offset off the time", () => {31+ expect(iso("2026-10-07T09:30:00+09:00")).toBe("2026-10-07T00:30:00.000Z");32+ expect(iso("2026-10-07T09:30:00+0900")).toBe("2026-10-07T00:30:00.000Z");33+ expect(iso("2026-10-06T20:30:00-03:30")).toBe("2026-10-07T00:00:00.000Z");34+ expect(iso("2026-10-07T14:30:00Z")).toBe("2026-10-07T14:30:00.000Z");35+ expect(iso("2026-10-07T00:00+05")).toBe("2026-10-06T19:00:00.000Z");36+ });37+38+ test("drops digits past the millisecond", () => {39+ expect(iso("2026-10-07T14:30:15.123456789Z")).toBe("2026-10-07T14:30:15.123Z");40+ expect(iso("2026-10-07T14:30:15,5Z")).toBe("2026-10-07T14:30:15.500Z");41+ });42+43+ test("reads February 29 only in a leap year", () => {44+ expect(iso("2028-02-29")).toBe("2028-02-29T00:00:00.000Z");45+ expect(isValid(parseISO("2026-02-29"))).toBe(false);46+ expect(isValid(parseISO("2100-02-29"))).toBe(false);47+ expect(iso("2000-02-29")).toBe("2000-02-29T00:00:00.000Z");48+ });49+50+ test("reads the years before 100 as written", () => {51+ expect(parseISO("0042-03-01").getUTCFullYear()).toBe(42);52+ });53+54+ test("gives an invalid date for text it can't read, and never throws", () => {55+ for (const text of [56+ "",57+ "next tuesday",58+ "2026-13-01",59+ "2026-10-32",60+ "2026-00-10",61+ "2026-367",62+ "2026-10-07T24:00",63+ "2026-10-07T14:60",64+ "2026-10-07T14:30:00+24:00",65+ "2026-10-07T14:30T15:00",66+ "26-10-07",67+ ]) {68+ expect(isValid(parseISO(text)), text).toBe(false);69+ }70+ });71+});72+73+describe("isValid", () => {74+ test("tells a real instant from an invalid date", () => {75+ expect(isValid(new Date(0))).toBe(true);76+ expect(isValid(new Date(Number.NaN))).toBe(false);77+ });78+});added:.env.schema+21 added
1+# The variables datekit's docs site and release step read. Values for tests2+# are in .env.test; a maintainer sets the release token, which is never3+# committed.4+# @currentEnv=$APP_ENV5+# @defaultRequired=infer @defaultSensitive=false6+# ---7+8+# @type=enum(development, test, production)9+APP_ENV=development10+11+# Error reporting DSN. Public: it ships in builds.12+# @type=url13+SENTRY_DSN=https://public@o0.ingest.example.invalid/114+15+# Source-map upload token. Release step only; never enters a check.16+# @sensitive @required=forEnv(production) @tag(release)17+# @proxy(domain="sentry.io", path="/api/**")18+SENTRY_AUTH_TOKEN=19+20+# Where locale data lives.21+DATEKIT_LOCALE_DIR=./localesadded:.env.test+3 added
1+# Values for APP_ENV=test. Committed: none of them is a secret.2+SENTRY_DSN=https://test@o0.ingest.example.invalid/23+DATEKIT_LOCALE_DIR=./localesadded:.gitignore+6 added
1+node_modules/2+3+# Values stay on each machine; .env.schema and .env.test are committed.4+.env5+.env.local6+.env.*.localadded:LICENSE+21 added
1+MIT License2+3+Copyright (c) 2026 The datekit authors4+5+Permission is hereby granted, free of charge, to any person obtaining a copy6+of this software and associated documentation files (the "Software"), to deal7+in the Software without restriction, including without limitation the rights8+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell9+copies of the Software, and to permit persons to whom the Software is10+furnished to do so, subject to the following conditions:11+12+The above copyright notice and this permission notice shall be included in all13+copies or substantial portions of the Software.14+15+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR16+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,17+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE18+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER19+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 THE21+SOFTWARE.added:package.json+24 added
1+{2+ "name": "datekit",3+ "version": "0.4.2",4+ "description": "Small, dependency-free date helpers for TypeScript: read ISO 8601, format with patterns, add and diff in whole units, in UTC or any time zone.",5+ "keywords": [6+ "date",7+ "format",8+ "iso8601",9+ "parse",10+ "time",11+ "timezone"12+ ],13+ "license": "MIT",14+ "files": [15+ "src"16+ ],17+ "type": "module",18+ "exports": {19+ ".": "./src/index.ts"20+ },21+ "scripts": {22+ "test": "bun test"23+ }24+}added:README.md+114 added
1+# datekit2+3+Small, dependency-free date helpers for TypeScript. datekit reads ISO 8601 text, shows dates with patterns, and adds and diffs in whole units. Dates are plain `Date` instants, and datekit works in UTC unless you name a time zone, so the same code gives the same answer on every machine.4+5+> datekit and its maintainers are fictional: it is an example project made up to show Myr, the git platform it is hosted on.6+7+## Install8+9+```sh10+bun add datekit11+```12+13+datekit has no dependencies and ships its TypeScript source, which Bun, Deno and any bundler read as is. It needs a runtime with `Intl` time zone data for the `timeZone` option; Bun, Deno, Node and every current browser have it.14+15+## Usage16+17+```ts18+import { addMonths, diffInDays, format, parseISO } from "datekit";19+20+const shipped = parseISO("2026-10-07T14:30:00+01:00");21+22+format(shipped, "EEE, d MMMM yyyy 'at' HH:mm"); // "Wed, 7 October 2026 at 13:30"23+format(shipped, "h:mm a XXX", { timeZone: "Asia/Tokyo" }); // "10:30 PM +09:00"24+25+const renewal = addMonths(shipped, 3);26+format(renewal, "yyyy-MM-dd"); // "2027-01-07"27+diffInDays(renewal, shipped); // 9228+```29+30+## Reading dates31+32+`parseISO(text)` reads ISO 8601:33+34+- a calendar date: `2026-10-07`, or `20261007`; `2026-10` is the month's first day and `2026` is January 1;35+- an ordinal date: `2026-280` is the 280th day of 2026;36+- then optionally `T` and a time, `14:30`, `14:30:15` or `14:30:15.250`, with a UTC offset, `Z`, `+09:00` or `-0330`.37+38+Text with no offset is read as UTC. Digits past the millisecond are dropped, not rounded.39+40+`parseISO` never throws. Text it can't read, or a day that doesn't exist (`2026-02-29`, `2026-04-31`), gives an invalid date; check with `isValid(date)`.41+42+## Showing dates43+44+`format(date, pattern, options?)` shows a date with a pattern, in UTC or in `options.timeZone`.45+46+| Token | Shows | Example |47+| --- | --- | --- |48+| `yyyy`, `yy` | year | `2026`, `26` |49+| `MMMM`, `MMM`, `MM`, `M` | month | `October`, `Oct`, `10`, `10` |50+| `Do`, `dd`, `d` | day of the month | `7th`, `07`, `7` |51+| `EEEE`, `EEE` | day of the week | `Wednesday`, `Wed` |52+| `HH`, `H` | hour, 24-hour clock | `14`, `14` |53+| `hh`, `h`, `a` | hour, 12-hour clock, and AM or PM | `02`, `2`, `PM` |54+| `mm`, `ss`, `SSS` | minute, second, millisecond | `05`, `09`, `250` |55+| `XXX` | UTC offset | `Z`, `+09:00`, `-04:00` |56+57+### Format patterns58+59+- Text in single quotes is printed exactly as written: `'Week of' MMMM d` is `Week of October 7`. Two single quotes print one: `h 'o''clock'` is `2 o'clock`.60+- Punctuation, digits and spaces pass through as they are.61+- A letter outside quotes that is no token throws a `RangeError`, so a typo never prints a wrong date. So does an invalid date, or a time zone the runtime doesn't know.62+63+## Moving dates64+65+`addMilliseconds`, `addSeconds`, `addMinutes`, `addHours`, `addDays`, `addWeeks`, `addMonths` and `addYears` each return a new date and leave their argument alone. Amounts are whole numbers; a fraction is dropped toward zero. Every day in UTC is 24 hours long, so `addDays` adds exact days. `addMonths` keeps the day of the month and the time of day, and `addYears` adds twelve months.66+67+## Comparing dates68+69+The `diffIn…` functions take the later date first and count whole units, dropping a part unit toward zero, so the result is negative when the first date is the earlier one.70+71+| Function | Counts |72+| --- | --- |73+| `diffInMilliseconds`, `diffInSeconds`, `diffInMinutes`, `diffInHours` | exact time |74+| `diffInDays`, `diffInWeeks` | whole 24-hour days and weeks |75+| `diffInCalendarDays` | UTC midnights crossed |76+| `diffInCalendarMonths` | month boundaries crossed |77+78+`isLeapYear(year)`, `daysInMonth(year, month)` (months 1 to 12) and `daysInYear(year)` answer calendar questions.79+80+## Time zones81+82+datekit keeps instants and never shifts them; a time zone only changes how a date is shown. `format` takes any IANA zone (`Europe/Lisbon`, `America/New_York`) and follows its daylight saving time. `zonedParts(date, timeZone)` gives the wall-clock fields and the offset, `offsetIn(date, timeZone)` the offset alone in minutes east of UTC, and `isTimeZone(name)` says whether the runtime knows a zone. The zone data is the runtime's own, so datekit ships none.83+84+## Contributing85+86+What we want changed is written down as asks, one file each in `.myr/asks/`: a sentence saying what should happen, and a test in `test/asks/` that fails until it does. To answer one:87+88+```sh89+myr asks --project datekit # what is open90+myr ask format-ordinal # read one in full91+myr claim format-ordinal # take it; this prints your fork's remote92+git remote add myr <remote> # the remote the claim printed93+myr check # run its test and the suite, as the platform will94+git push myr HEAD:main # offer your answer95+```96+97+The platform runs the ask's test and the rest of the suite on your answer, and lands it on main with your name on it when both pass. An answer changes only the files its ask names. `format-ordinal` is kept for newcomers, with okonkwo as mentor.98+99+Claiming needs a vouch: a line in `.myr/vouched.td`. Anyone not denounced there may propose an ask with `myr propose`.100+101+Run the tests with `bun test`. On main, the three asks' tests fail; everything else passes.102+103+## Environment104+105+`.env.schema` declares the variables the docs site and the release step read, in varlock's `@env-spec` format. Test values are committed in `.env.test`. The source-map upload token is set by a maintainer for releases and never committed, and no check ever sees it.106+107+## Maintainers108+109+- `ines-v` decides for the whole library.110+- `okonkwo` decides for time zones (`src/tz.ts`).111+112+## License113+114+MITadded:tsconfig.json+16 added
1+{2+ "compilerOptions": {3+ "target": "ES2023",4+ "lib": ["ES2023"],5+ "module": "Preserve",6+ "moduleResolution": "bundler",7+ "allowImportingTsExtensions": true,8+ "noEmit": true,9+ "strict": true,10+ "noUncheckedIndexedAccess": true,11+ "exactOptionalPropertyTypes": true,12+ "verbatimModuleSyntax": true,13+ "skipLibCheck": true14+ },15+ "include": ["src", "test"]16+}