A collection of utility functions for working with JavaScript dates.
pnpm add @pixpilot/dateimport {
addDays,
diffDays,
formatISODate,
isDate,
isValidDate,
parseDateOrNull,
} from '@pixpilot/date';
// Parse dates safely
const date = parseDateOrNull('2023-01-15'); // Date or null
// Type guards
if (isValidDate(value)) {
// value is a valid Date object
}
// Date manipulation
const tomorrow = addDays(new Date(), 1);
const daysDiff = diffDays(new Date('2023-01-01'), new Date('2023-01-10')); // 9
// Formatting
const formatted = formatISODate(new Date()); // '2023-01-15'isDate(value: unknown): value is Date- Check if value is a Date objectisValidDate(value: unknown): value is Date- Check if value is a valid Date (not Invalid Date)
parseDateOrNull(value: unknown): Date | null- Parse a value as a Date, return null if invalid
addDays(date: Date, days: number): Date- Add days to a dateaddMonths(date: Date, months: number): Date- Add months to a dateaddYears(date: Date, years: number): Date- Add years to a dateaddHours(date: Date, hours: number): Date- Add hours to a dateaddMinutes(date: Date, minutes: number): Date- Add minutes to a date
diffDays(date1: Date, date2: Date): number- Calculate difference in daysdiffHours(date1: Date, date2: Date): number- Calculate difference in hoursdiffMinutes(date1: Date, date2: Date): number- Calculate difference in minutes
startOfDay(date: Date): Date- Get start of day (00:00:00.000)endOfDay(date: Date): Date- Get end of day (23:59:59.999)startOfMonth(date: Date): Date- Get start of monthendOfMonth(date: Date): Date- Get end of month
isSameDay(date1: Date, date2: Date): boolean- Check if dates are on the same dayisPast(date: Date): boolean- Check if date is in the pastisFuture(date: Date): boolean- Check if date is in the futureisToday(date: Date): boolean- Check if date is today
formatISODate(date: Date): string- Format as ISO date string (YYYY-MM-DD)formatISODateTime(date: Date): string- Format as ISO datetime string (YYYY-MM-DDTHH:mm:ss)
getDaysInMonth(year: number, month: number): number- Get number of days in a monthisLeapYear(year: number): boolean- Check if year is a leap year
We welcome contributions! Please see the main contributing guide for details.
This project is licensed under the MIT License. See the LICENSE file for details.