add.ts
This file
Path
examples/datekit/src/add.ts
39 lines · 1.5 KiB · TypeScript
Last changed by
Not known.
History of this fileTake it
The walk stopped after 200 commits: lines older than 678c8b8 point at it.
Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 1–39why, one step back1/**2 * Moving a date by whole units. Each function returns a new date and leaves3 * its argument alone. Amounts are whole numbers: a fraction is dropped4 * toward zero (`addDays(date, 1.9)` adds one day). An invalid date stays5 * invalid.6 */7import { MS_PER_DAY, MS_PER_HOUR, MS_PER_MINUTE, MS_PER_SECOND } from "./calendar.ts";89const by = (date: Date, amount: number, unit: number): Date =>10 new Date(date.getTime() + Math.trunc(amount) * unit);1112export const addMilliseconds = (date: Date, amount: number): Date => by(date, amount, 1);1314export const addSeconds = (date: Date, amount: number): Date => by(date, amount, MS_PER_SECOND);1516export const addMinutes = (date: Date, amount: number): Date => by(date, amount, MS_PER_MINUTE);1718export const addHours = (date: Date, amount: number): Date => by(date, amount, MS_PER_HOUR);1920/** Adds days. datekit works in UTC, where every day is 24 hours long. */21export const addDays = (date: Date, amount: number): Date => by(date, amount, MS_PER_DAY);2223export const addWeeks = (date: Date, amount: number): Date => addDays(date, Math.trunc(amount) * 7);2425/**26 * Adds calendar months, keeping the day of the month and the time of day:27 * October 7 plus three months is January 7.28 */29export const addMonths = (date: Date, amount: number): Date => {30 const next = new Date(date.getTime());3132 next.setUTCMonth(next.getUTCMonth() + Math.trunc(amount));3334 return next;35};3637/** Adds calendar years: twelve months each. */38export const addYears = (date: Date, amount: number): Date =>39 addMonths(date, Math.trunc(amount) * 12);