add.ts
This file
Path
src/add.ts
51 lines · 2.0 KiB · TypeScript
Last changed by
add-months-clampanswered by oscard88535c
History of this fileTake it
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152/** * 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, daysInMonth,} 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. When the target month is too * short for the day, the result ends on its last day: January 31 plus one * month is February 29 in a leap year and February 28 otherwise. */export const addMonths = (date: Date, amount: number): Date => { const next = new Date(date.getTime()); const day = next.getUTCDate();
// Move from the 1st so the month can't run over, then clamp the day to it. next.setUTCDate(1); next.setUTCMonth(next.getUTCMonth() + Math.trunc(amount)); next.setUTCDate(Math.min(day, daysInMonth(next.getUTCFullYear(), next.getUTCMonth() + 1)));
return next;};
/** Adds calendar years: twelve months each, so February 29 plus a year is February 28. */export const addYears = (date: Date, amount: number): Date => addMonths(date, Math.trunc(amount) * 12);