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
1/**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 {8 MS_PER_DAY,9 MS_PER_HOUR,10 MS_PER_MINUTE,11 MS_PER_SECOND,12 daysInMonth,13} from "./calendar.ts";1415const by = (date: Date, amount: number, unit: number): Date =>16 new Date(date.getTime() + Math.trunc(amount) * unit);1718export const addMilliseconds = (date: Date, amount: number): Date => by(date, amount, 1);1920export const addSeconds = (date: Date, amount: number): Date => by(date, amount, MS_PER_SECOND);2122export const addMinutes = (date: Date, amount: number): Date => by(date, amount, MS_PER_MINUTE);2324export const addHours = (date: Date, amount: number): Date => by(date, amount, MS_PER_HOUR);2526/** Adds days. datekit works in UTC, where every day is 24 hours long. */27export const addDays = (date: Date, amount: number): Date => by(date, amount, MS_PER_DAY);2829export const addWeeks = (date: Date, amount: number): Date => addDays(date, Math.trunc(amount) * 7);3031/**32 * Adds calendar months, keeping the day of the month and the time of day:33 * October 7 plus three months is January 7. When the target month is too34 * short for the day, the result ends on its last day: January 31 plus one35 * month is February 29 in a leap year and February 28 otherwise.36 */37export const addMonths = (date: Date, amount: number): Date => {38 const next = new Date(date.getTime());39 const day = next.getUTCDate();4041 // Move from the 1st so the month can't run over, then clamp the day to it.42 next.setUTCDate(1);43 next.setUTCMonth(next.getUTCMonth() + Math.trunc(amount));44 next.setUTCDate(Math.min(day, daysInMonth(next.getUTCFullYear(), next.getUTCMonth() + 1)));4546 return next;47};4849/** Adds calendar years: twelve months each, so February 29 plus a year is February 28. */50export const addYears = (date: Date, amount: number): Date =>51 addMonths(date, Math.trunc(amount) * 12);