Skip to content
Myr

Start oscabriel/datekit

Landed as 6a2b761

authored by oscabriel · committed by the platform · the first commit · Browse files · 21 files+1112 added−0 removed
This landing

State

Landed as 6a2b761

By oscabriel

Diff stats

21 files+1112 added−0 removed

  • tests:+325 added−0 removed
  • other:+787 added−0 removed

21 files+1112 added−0 removed

added:.myr/project.ts+23 added
added:.myr/visibility.ts+26 added
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.9bram first answer landed in 0.4.010ines-v maintainer11okonkwo maintainer, time zones
added:src/add.ts+39 added
added:src/calendar.ts+38 added
added:src/diff.ts+45 added
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 */7import { isValid } from "./parse.ts";8import { utcParts, zonedParts } from "./tz.ts";9import type { ZonedParts } from "./tz.ts";1011/** How `format` shows a date. */12export interface FormatOptions {13 /** The IANA zone to show the date in (`America/New_York`); UTC when left out. */14 readonly timeZone?: string;15}1617const 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];3132const WEEKDAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];3334const pad = (value: number, width: number) => String(value).padStart(width, "0");3536// The English suffix by last digit: 1st, 2nd, 3rd, and th for the rest.37const SUFFIXES = ["th", "st", "nd", "rd"];3839/** A number as an English ordinal: `1st`, `2nd`, `3rd`, `4th`. */40export const ordinal = (value: number): string => `${value}${SUFFIXES[value % 10] ?? "th"}`;4142/** A UTC offset as `Z`, or `+09:00`, `-04:00`, `+05:30`. */43const offsetText = (minutes: number) => {44 if (minutes === 0) {45 return "Z";46 }4748 const sign = minutes < 0 ? "-" : "+";49 const size = Math.abs(minutes);5051 return `${sign}${pad(Math.floor(size / 60), 2)}:${pad(size % 60, 2)}`;52};5354const twelveHour = (hour: number) => hour % 12 || 12;5556/** Each token, and how it shows a date's fields. */57const 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};8586// 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.88const PIECES = /'(?:[^']|'')*(?:'|$)|Do|([A-Za-z])\1*|[^A-Za-z']+/gu;8990/** One piece of a pattern, shown. */91const show = (piece: string, parts: ZonedParts): string => {92 if (piece.startsWith("'")) {93 return piece === "''"94 ? "'"95 : piece.slice(1, piece.endsWith("'") ? -1 : undefined).replaceAll("''", "'");96 }9798 if (!/^[A-Za-z]/u.test(piece)) {99 return piece;100 }101102 const token = TOKENS[piece];103104 if (token === undefined) {105 throw new RangeError(`format: "${piece}" is not a token; quote literal text, like 'at'`);106 }107108 return token(parts);109};110111/**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 */125export const format = (date: Date, pattern: string, options: FormatOptions = {}): string => {126 if (!isValid(date)) {127 throw new RangeError("format: the date is invalid");128 }129130 const parts =131 options.timeZone === undefined ? utcParts(date) : zonedParts(date, options.timeZone);132133 return (pattern.match(PIECES) ?? []).map((piece) => show(piece, parts)).join("");134};
added:src/index.ts+28 added
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 */6import {7 MS_PER_HOUR,8 MS_PER_MINUTE,9 MS_PER_SECOND,10 daysInMonth,11 daysInYear,12 utcMidnight,13} from "./calendar.ts";1415/** A date that stands for no instant: what `parseISO` gives for text it can't read. */16export const invalidDate = (): Date => new Date(Number.NaN);1718/** Whether `date` stands for an instant (an invalid date doesn't). */19export const isValid = (date: Date): boolean => !Number.isNaN(date.getTime());2021/** The date forms `parseISO` reads, extended and basic. */22const 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];2829const ORDINAL_DATE = /^(?<year>\d{4})-?(?<ordinal>\d{3})$/u;3031const TIME =32 /^(?<hour>\d{2})(?::(?<minute>\d{2})(?::(?<second>\d{2})(?:[.,](?<fraction>\d{1,9}))?)?)?(?<offset>Z|[+-]\d{2}(?::?\d{2})?)?$/u;3334const OFFSET = /^(?<sign>[+-])(?<hours>\d{2}):?(?<minutes>\d{2})?$/u;3536const whole = (digits: string | undefined, fallback = 0): number =>37 digits === undefined ? fallback : Number(digits);3839/** A calendar date, as the instant it starts in UTC; `undefined` when it isn't a real day. */40const 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;4445/** The start of the day the date part names, in epoch milliseconds. */46const readDate = (text: string): number | undefined => {47 for (const form of CALENDAR_DATES) {48 const groups = form.exec(text)?.groups;4950 if (groups !== undefined) {51 return calendarDay(whole(groups.year), whole(groups.month, 1), whole(groups.day, 1));52 }53 }5455 const ordinal = ORDINAL_DATE.exec(text)?.groups;5657 if (ordinal !== undefined) {58 const year = whole(ordinal.year);59 const day = whole(ordinal.ordinal);6061 return day >= 1 && day <= daysInYear(year) ? utcMidnight(year, 1, day) : undefined;62 }6364 return undefined;65};6667/** A UTC offset (`Z`, `+09:00`, `-0330`, `+05`) in minutes east of UTC. */68const readOffset = (text: string | undefined): number | undefined => {69 if (text === undefined || text === "Z") {70 return 0;71 }7273 const groups = OFFSET.exec(text)?.groups;7475 if (groups === undefined) {76 return undefined;77 }7879 const hours = whole(groups.hours);80 const minutes = whole(groups.minutes);8182 if (hours > 23 || minutes > 59) {83 return undefined;84 }8586 return (groups.sign === "-" ? -1 : 1) * (hours * 60 + minutes);87};8889/** How far past midnight the time part is, in UTC milliseconds (its offset taken off). */90const readTime = (text: string): number | undefined => {91 const groups = TIME.exec(text)?.groups;9293 if (groups === undefined) {94 return undefined;95 }9697 const hour = whole(groups.hour);98 const minute = whole(groups.minute);99 const second = whole(groups.second);100 const offset = readOffset(groups.offset);101102 if (hour > 23 || minute > 59 || second > 59 || offset === undefined) {103 return undefined;104 }105106 // Digits past the millisecond are dropped, not rounded.107 const millisecond = whole((groups.fraction ?? "").padEnd(3, "0").slice(0, 3));108109 return (110 hour * MS_PER_HOUR +111 minute * MS_PER_MINUTE +112 second * MS_PER_SECOND +113 millisecond -114 offset * MS_PER_MINUTE115 );116};117118/**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 */125export const parseISO = (text: string): Date => {126 const [datePart = "", timePart, ...rest] = text.trim().split("T");127 const day = readDate(datePart);128129 if (day === undefined || rest.length > 0) {130 return invalidDate();131 }132133 if (timePart === undefined) {134 return new Date(day);135 }136137 const time = readTime(timePart);138139 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 */8import { MS_PER_MINUTE, isoWeekday, utcMidnight } from "./calendar.ts";910/** An instant's wall-clock fields in one zone, and the zone's offset from UTC then. */11export 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}2627/** An instant's fields in UTC. */28export 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});3940/** Whether the runtime knows `name` as a time zone. */41export const isTimeZone = (name: string): boolean => {42 try {43 new Intl.DateTimeFormat("en-US", { timeZone: name });4445 return true;46 } catch {47 return false;48 }49};5051const 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 });6263/**64 * An instant's fields in the IANA zone `timeZone`. Throws a `RangeError`65 * for a zone the runtime doesn't know.66 */67export 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 );7374 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")));7778 // 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;8384 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};9697/** The offset of `timeZone` from UTC at `date`, in minutes east of UTC. */98export const offsetIn = (date: Date, timeZone: string): number => zonedParts(date, timeZone).offset;
added:test/add.test.ts+79 added
added:test/diff.test.ts+73 added
1import { describe, expect, test } from "bun:test";23import {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";1516const at = (text: string) => new Date(text);1718describe("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 });2526 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 });3031 test("gives NaN for an invalid date", () => {32 expect(diffInDays(new Date(Number.NaN), at("2026-10-07T00:00:00Z"))).toBeNaN();33 });34});3536describe("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});4344describe("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});5152describe("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");5657 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});6465describe("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
1import { describe, expect, test } from "bun:test";23import { format, isTimeZone, offsetIn } from "../src/index.ts";45// Wednesday, October 7, 2026, 14:05:09.250 UTC.6const afternoon = new Date(Date.UTC(2026, 9, 7, 14, 5, 9, 250));78const on = (year: number, month: number, day: number, hour = 0, minute = 0) =>9 new Date(Date.UTC(year, month - 1, day, hour, minute));1011describe("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 });1819 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 });2627 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];2930 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 });4546 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 });5253 test("passes punctuation and spaces through", () => {54 expect(format(afternoon, "[yyyy] (MM) / dd.")).toBe("[2026] (10) / 07.");55 });5657 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 });6364 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});6869describe("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 });7273 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 });7980 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 });9091 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
1import { describe, expect, test } from "bun:test";23import { isValid, parseISO } from "../src/index.ts";45const iso = (text: string) => parseISO(text).toISOString();67describe("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 });1213 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 });1718 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 });2324 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 });2930 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 });3738 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 });4243 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 });4950 test("reads the years before 100 as written", () => {51 expect(parseISO("0042-03-01").getUTCFullYear()).toBe(42);52 });5354 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});7273describe("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# ---78# @type=enum(development, test, production)9APP_ENV=development1011# Error reporting DSN. Public: it ships in builds.12# @type=url13SENTRY_DSN=https://public@o0.ingest.example.invalid/11415# 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/**")18SENTRY_AUTH_TOKEN=1920# Where locale data lives.21DATEKIT_LOCALE_DIR=./locales
added:.env.test+3 added
1# Values for APP_ENV=test. Committed: none of them is a secret.2SENTRY_DSN=https://test@o0.ingest.example.invalid/23DATEKIT_LOCALE_DIR=./locales
added:.gitignore+6 added
1node_modules/23# Values stay on each machine; .env.schema and .env.test are committed.4.env5.env.local6.env.*.local
added:LICENSE+21 added
1MIT License23Copyright (c) 2026 The datekit authors45Permission is hereby granted, free of charge, to any person obtaining a copy6of this software and associated documentation files (the "Software"), to deal7in the Software without restriction, including without limitation the rights8to use, copy, modify, merge, publish, distribute, sublicense, and/or sell9copies of the Software, and to permit persons to whom the Software is10furnished to do so, subject to the following conditions:1112The above copyright notice and this permission notice shall be included in all13copies or substantial portions of the Software.1415THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR16IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,17FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE18AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER19LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,20OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE21SOFTWARE.
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# datekit23Small, 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.45> datekit and its maintainers are fictional: it is an example project made up to show Myr, the git platform it is hosted on.67## Install89```sh10bun add datekit11```1213datekit 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.1415## Usage1617```ts18import { addMonths, diffInDays, format, parseISO } from "datekit";1920const shipped = parseISO("2026-10-07T14:30:00+01:00");2122format(shipped, "EEE, d MMMM yyyy 'at' HH:mm"); // "Wed, 7 October 2026 at 13:30"23format(shipped, "h:mm a XXX", { timeZone: "Asia/Tokyo" }); // "10:30 PM +09:00"2425const renewal = addMonths(shipped, 3);26format(renewal, "yyyy-MM-dd"); // "2027-01-07"27diffInDays(renewal, shipped); // 9228```2930## Reading dates3132`parseISO(text)` reads ISO 8601:3334- 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`.3738Text with no offset is read as UTC. Digits past the millisecond are dropped, not rounded.3940`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)`.4142## Showing dates4344`format(date, pattern, options?)` shows a date with a pattern, in UTC or in `options.timeZone`.4546| 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` |5657### Format patterns5859- 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.6263## Moving dates6465`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.6667## Comparing dates6869The `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.7071| 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 |7778`isLeapYear(year)`, `daysInMonth(year, month)` (months 1 to 12) and `daysInYear(year)` answer calendar questions.7980## Time zones8182datekit 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.8384## Contributing8586What 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:8788```sh89myr asks --project datekit # what is open90myr ask format-ordinal # read one in full91myr claim format-ordinal # take it; this prints your fork's remote92git remote add myr <remote> # the remote the claim printed93myr check # run its test and the suite, as the platform will94git push myr HEAD:main # offer your answer95```9697The 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.9899Claiming needs a vouch: a line in `.myr/vouched.td`. Anyone not denounced there may propose an ask with `myr propose`.100101Run the tests with `bun test`. On main, the three asks' tests fail; everything else passes.102103## Environment104105`.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.106107## Maintainers108109- `ines-v` decides for the whole library.110- `okonkwo` decides for time zones (`src/tz.ts`).111112## License113114MIT
added: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}