@mfuon2/chrono-utilz
Version:
A comprehensive date utility library built on Three Pillars Architecture: Core Operations (45+ functions), Business Utilities (55+ functions), and Formatting & Parsing (35+ functions). Features natural language parsing, timezone conversion, fiscal periods
1,556 lines (1,554 loc) • 69.8 kB
text/typescript
/**
* Get user's current timezone using Intl API
* @returns {string} The user's IANA timezone identifier
*/
declare function getUserTimezone(): string;
/**
* Get all available timezones filtered by region
* @param region - Region to filter by (e.g., 'America', 'Europe', 'Asia')
* @returns Array of timezone objects in the specified region
*/
declare function getTimezonesByRegion(region: string): Array<{
id: string;
offset: number;
description: string;
}>;
/**
* Search timezones by description or ID
* @param query - Search query
* @returns Array of matching timezone objects
*/
declare function searchTimezones(query: string): Array<{
id: string;
offset: number;
description: string;
}>;
/**
* Get timezones by GMT offset
* @param offset - GMT offset in hours
* @returns Array of timezone objects with the specified offset
*/
declare function getTimezonesByOffset(offset: number): Array<{
id: string;
offset: number;
description: string;
}>;
/**
* Create a comprehensive timezone type for TypeScript
*/
declare const TIMEZONE_IDS: string[];
/**
* ChronoUtilz - A comprehensive date utility library built on Three Pillars Architecture
*
* Three Pillars Architecture:
* - Core Operations (45+ functions): Date manipulation & comparison
* - Business Utilities (55+ functions): Real-world business logic
* - Formatting & Parsing (35+ functions): Advanced presentation
*
* 🚀 Business-Ready Features:
* - Working days with holiday support
* - Fiscal quarters and periods
* - Natural language parsing ("next Friday")
* - Timezone conversion between IANA zones
* - Recurring date patterns
* - Advanced duration calculations
*
* Compatible with TypeScript, JavaScript and Node.js
* @module ChronoUtilz
* @version 2.0.0
*/
/**
* Configure global timezone behavior for ChronoUtilz
* @param config - Timezone configuration
*/
declare function configureTimezone(config: {
defaultTimezone?: IANATimezone;
autoDetect?: boolean;
}): void;
/**
* Get current timezone configuration
* @returns Current configuration
*/
declare function getTimezoneConfig(): {
defaultTimezone: string;
autoDetect: boolean;
currentEffectiveTimezone: string;
};
/**
* DateFormat options for formatting dates
*/
type DateFormat = 'YYYY-MM-DD' | 'MM/DD/YYYY' | 'DD/MM/YYYY' | 'YYYY-MM-DD HH:mm:ss' | 'DD MMM YYYY' | 'MMM DD, YYYY' | 'HH:mm:ss' | 'hh:mm A';
/**
* TimeUnit for duration calculations
*/
type TimeUnit = 'millisecond' | 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year';
/**
* IANA Timezone identifiers - Complete standardized list
*/
type IANATimezone = typeof TIMEZONE_IDS[number] | string;
/**
* Natural language time expressions
*/
type NaturalTimeExpression = 'now' | 'today' | 'tomorrow' | 'yesterday' | 'next week' | 'last week' | 'next month' | 'last month' | 'next year' | 'last year' | 'next monday' | 'next tuesday' | 'next wednesday' | 'next thursday' | 'next friday' | 'next saturday' | 'next sunday' | 'last monday' | 'last tuesday' | 'last wednesday' | 'last thursday' | 'last friday' | 'last saturday' | 'last sunday' | 'beginning of week' | 'end of week' | 'beginning of month' | 'end of month' | 'beginning of year' | 'end of year' | string;
/**
* Recurring pattern types
*/
type RecurringPattern = 'daily' | 'weekly' | 'biweekly' | 'monthly' | 'quarterly' | 'yearly' | 'weekdays' | 'weekends' | 'custom';
/**
* Fiscal year configuration
*/
interface FiscalYearConfig {
startMonth: number;
startDay: number;
}
/**
* ChronoUtilz options for parsing dates
*/
interface DateParseOptions {
/**
* Whether to throw an error if the date is invalid
*/
throwError?: boolean;
/**
* The fallback date to use if parsing fails
*/
fallback?: Date | null;
/**
* Timezone to use for parsing (defaults to user's timezone)
*/
timezone?: IANATimezone;
}
/**
* Timezone conversion options
*/
interface TimezoneConversionOptions {
from?: IANATimezone;
to: IANATimezone;
preserveTime?: boolean;
}
/**
* Timezone conversion options
*/
interface TimezoneConversionOptions {
from?: IANATimezone;
to: IANATimezone;
preserveTime?: boolean;
}
/**
* Advanced formatting options
*/
interface AdvancedFormatOptions {
locale?: string;
timezone?: IANATimezone;
includeTime?: boolean;
includeSeconds?: boolean;
use24Hour?: boolean;
includeDayOfWeek?: boolean;
includeTimezone?: boolean;
}
/**
* Advanced formatting options
*/
interface AdvancedFormatOptions {
locale?: string;
timezone?: IANATimezone;
includeTime?: boolean;
includeSeconds?: boolean;
use24Hour?: boolean;
includeDayOfWeek?: boolean;
includeTimezone?: boolean;
}
/**
* Recurring date configuration
*/
interface RecurringConfig {
pattern: RecurringPattern;
interval?: number;
daysOfWeek?: number[];
daysOfMonth?: number[];
monthsOfYear?: number[];
endDate?: Date;
maxOccurrences?: number;
}
/**
* Recurring date configuration
*/
interface RecurringConfig {
pattern: RecurringPattern;
interval?: number;
daysOfWeek?: number[];
daysOfMonth?: number[];
monthsOfYear?: number[];
endDate?: Date;
maxOccurrences?: number;
}
/**
* Natural language parsing options
*/
interface NaturalLanguageOptions {
baseDate?: Date;
timezone?: IANATimezone;
strictParsing?: boolean;
}
/**
* Natural language parsing options
*/
interface NaturalLanguageOptions {
baseDate?: Date;
timezone?: IANATimezone;
strictParsing?: boolean;
}
/**
* Duration display options
*/
interface DurationDisplayOptions {
precision?: number;
units?: TimeUnit[];
format?: 'long' | 'short' | 'narrow';
separator?: string;
includeZeroValues?: boolean;
}
/**
* Duration display options
*/
interface DurationDisplayOptions {
precision?: number;
units?: TimeUnit[];
format?: 'long' | 'short' | 'narrow';
separator?: string;
includeZeroValues?: boolean;
}
/**
* Holiday configuration
*/
interface HolidayConfig {
country?: string;
region?: string;
includeObserved?: boolean;
customHolidays?: Date[];
}
/**
* Holiday configuration
*/
interface HolidayConfig {
country?: string;
region?: string;
includeObserved?: boolean;
customHolidays?: Date[];
}
/**
* Working time configuration
*/
interface WorkingTimeConfig {
startHour: number;
endHour: number;
workingDays: number[];
timezone?: IANATimezone;
excludeHolidays?: boolean;
holidayConfig?: HolidayConfig;
}
/**
* Working time configuration
*/
interface WorkingTimeConfig {
startHour: number;
endHour: number;
workingDays: number[];
timezone?: IANATimezone;
excludeHolidays?: boolean;
holidayConfig?: HolidayConfig;
}
/**
* Date comparison result
*/
interface DateComparison {
isBefore: boolean;
isAfter: boolean;
isSame: boolean;
difference: {
years: number;
months: number;
days: number;
hours: number;
minutes: number;
seconds: number;
milliseconds: number;
};
}
/**
* Date comparison result
*/
interface DateComparison {
isBefore: boolean;
isAfter: boolean;
isSame: boolean;
difference: {
years: number;
months: number;
days: number;
hours: number;
minutes: number;
seconds: number;
milliseconds: number;
};
}
/**
* Fiscal period information
*/
interface FiscalPeriod {
quarter: number;
year: number;
startDate: Date;
endDate: Date;
isCurrentPeriod: boolean;
}
/**
* Fiscal period information
*/
interface FiscalPeriod {
quarter: number;
year: number;
startDate: Date;
endDate: Date;
isCurrentPeriod: boolean;
}
/**
* Calendar event interface
*/
interface CalendarEvent {
id?: string;
title: string;
startDate: Date;
endDate?: Date;
isAllDay?: boolean;
recurring?: RecurringConfig;
timezone?: IANATimezone;
}
/**
* Calendar event interface
*/
interface CalendarEvent {
id?: string;
title: string;
startDate: Date;
endDate?: Date;
isAllDay?: boolean;
recurring?: RecurringConfig;
timezone?: IANATimezone;
}
/**
* ChronoUtilz error class
*/
declare class ChronoUtilzError extends Error {
constructor(message: string);
}
/**
* Safely parses a date string or timestamp into a Date object
* @param input - The input to parse as a date
* @param options - Parsing options
* @returns A Date object or null if invalid and throwError is false
* @throws {ChronoUtilzError} If the date is invalid and throwError is true
*/
declare function parseDate(input: string | number | Date, options?: DateParseOptions): Date | null;
/**
* Formats a date according to the specified format
* @param date - The date to format
* @param format - The format pattern
* @returns Formatted date string
* @throws {ChronoUtilzError} If the date is invalid
*/
declare function formatDate(date: Date | string | number, format?: DateFormat, timezone?: IANATimezone): string;
/**
* Adds time to a date
* @param date - The base date
* @param amount - The amount to add
* @param unit - The time unit
* @returns A new Date with the added time
*/
declare function addTime(date: Date | string | number, amount: number, unit: TimeUnit, timezone?: IANATimezone): Date;
/**
* Subtracts time from a date
* @param date - The base date
* @param amount - The amount to subtract
* @param unit - The time unit
* @param timezone - Optional timezone (defaults to user's timezone)
* @returns A new Date with the subtracted time
*/
declare function subtractTime(date: Date | string | number, amount: number, unit: TimeUnit, timezone?: IANATimezone): Date;
/**
* Gets the difference between two dates in the specified unit
* @param date1 - The first date
* @param date2 - The second date
* @param unit - The time unit
* @returns The difference in the specified unit
*/
declare function getDateDiff(date1: Date | string | number, date2: Date | string | number, unit: TimeUnit, timezone?: IANATimezone): number;
/**
* Calculates remaining time until a target date, or elapsed time if past
* @param targetDate - The target date to calculate time to/from
* @param unit - The time unit to return (default: 'millisecond')
* @param referenceDate - Optional reference date (default: now)
* @param timezone - Optional timezone (defaults to user's timezone)
* @returns Positive number if target is in future (remaining time), negative if past (elapsed time)
*/
declare function remainingTime(targetDate: Date | string | number, unit?: TimeUnit, referenceDate?: Date | string | number, timezone?: IANATimezone): number;
/**
* Checks if a date is between two other dates
* @param date - The date to check
* @param startDate - The start date
* @param endDate - The end date
* @param inclusive - Whether to include the boundaries
* @returns True if the date is between the start and end dates
*/
declare function isBetweenDates(date: Date | string | number, startDate: Date | string | number, endDate: Date | string | number, inclusive?: boolean): boolean;
/**
* Validates whether a given input is a valid date in supported formats.
* Checks if a date is valid
* @param date - The date to check
* @returns True if the date is valid
*/
declare function isValidDate(date: any): boolean;
/**
* Gets the start of a time unit (e.g., start of day, start of month)
* @param date - The reference date
* @param unit - The time unit
* @returns A new Date representing the start of the specified unit
*/
declare function startOf(date: Date | string | number, unit: Exclude<TimeUnit, 'millisecond' | 'second' | 'minute'>): Date;
/**
* Gets the end of a time unit (e.g., end of day, end of month)
* @param date - The reference date
* @param unit - The time unit
* @returns A new Date representing the end of the specified unit
*/
declare function endOf(date: Date | string | number, unit: Exclude<TimeUnit, 'millisecond' | 'second' | 'minute'>): Date;
/**
* Gets the day of the year (1-366)
* @param date - The date
* @returns The day of the year
*/
declare function getDayOfYear(date: Date | string | number): number;
/**
* Gets the week of the year (1-53)
* @param date - The date
* @returns The week of the year
*/
declare function getWeekOfYear(date: Date | string | number): number;
/**
* Checks if a year is a leap year
* @param year - The year to check or a date
* @returns True if the year is a leap year
*/
declare function isLeapYear(year: number | Date | string): boolean;
/**
* Gets the number of days in a month
* @param date - The reference date
* @returns The number of days in the month
*/
declare function getDaysInMonth(date: Date | string | number): number;
/**
* Returns a relative time string (e.g., "5 minutes ago", "in 2 days")
* @param date - The date to get relative time for
* @param baseDate - The base date (defaults to now)
* @returns A human-readable relative time string
*/
declare function getRelativeTime(date: Date | string | number, baseDate?: Date | string | number): string;
/**
* Gets the timezone offset in minutes
* @param date - The date to get timezone offset for
* @returns Timezone offset in minutes
*/
declare function getTimezoneOffset(date?: Date | string | number): number;
/**
* Creates a date from components
* @param year - The year
* @param month - The month (0-11)
* @param day - The day (1-31)
* @param hours - The hours (0-23)
* @param minutes - The minutes (0-59)
* @param seconds - The seconds (0-59)
* @param milliseconds - The milliseconds (0-999)
* @returns A new Date object
*/
declare function createDate(year: number, month: number, day: number, hours?: number, minutes?: number, seconds?: number, milliseconds?: number): Date;
/**
* A calendar date without time information
*/
declare class CalendarDate {
private _year;
private _month;
private _day;
/**
* Creates a new CalendarDate
* @param year - The year
* @param month - The month (1-12)
* @param day - The day (1-31)
*/
constructor(year: number, month: number, day: number);
/**
* Creates a CalendarDate from a Date object
* @param date - The Date object
* @returns A new CalendarDate
*/
static fromDate(date: Date): CalendarDate;
/**
* Creates a CalendarDate from a string or timestamp
* @param input - The input to parse
* @returns A new CalendarDate
*/
static fromString(input: string | number): CalendarDate;
/**
* Gets the year
*/
get year(): number;
/**
* Gets the month (1-12)
*/
get month(): number;
/**
* Gets the day (1-31)
*/
get day(): number;
/**
* Converts to a JavaScript Date object (at midnight local time)
* @returns A new Date object
*/
toDate(): Date;
/**
* Returns an ISO date string (YYYY-MM-DD)
* @returns ISO date string
*/
toString(): string;
/**
* Adds time to this calendar date
* @param amount - The amount to add
* @param unit - The time unit (limited to day, week, month, year)
* @returns A new CalendarDate
*/
add(amount: number, unit: Extract<TimeUnit, 'day' | 'week' | 'month' | 'year'>): CalendarDate;
/**
* Checks if this calendar date is equal to another
* @param other - The other calendar date
* @returns True if the dates are equal
*/
equals(other: CalendarDate): boolean;
/**
* Compares this calendar date with another
* @param other - The other calendar date
* @returns Negative if this < other, 0 if equal, positive if this > other
*/
compare(other: CalendarDate): number;
/**
* Checks if this calendar date is before another
* @param other - The other calendar date
* @returns True if this date is before the other
*/
isBefore(other: CalendarDate): boolean;
/**
* Checks if this calendar date is after another
* @param other - The other calendar date
* @returns True if this date is after the other
*/
isAfter(other: CalendarDate): boolean;
}
/**
* Gets the current UTC date and time
* @returns The current UTC date and time
*/
declare function utcNow(): Date;
/**
* Converts a date to UTC
* @param date - The date to convert
* @returns A new Date in UTC
*/
declare function toUTC(date: Date | string | number): Date;
/**
* Gets a string representation of the current timezone
* @returns Timezone string (e.g., "UTC+2")
*/
declare function getTimezoneString(): string;
/**
* Validates if a date string matches a specific format
* @param dateStr - The date string to validate
* @param format - The expected format
* @returns True if the date string matches the format and is valid
*/
declare function validateDateFormat(dateStr: string, format: DateFormat): boolean;
/**
* Options for date range generation
*/
interface DateRangeOptions {
/** The start date of the range */
start: Date | string;
/** The end date of the range */
end: Date | string;
/** The increment unit (default: 'day') */
unit?: TimeUnit;
/** The increment value (default: 1) */
step?: number;
/** Whether to include the end date (default: true) */
inclusive?: boolean;
}
/**
* Generates an array of dates between a start and end date
*
* @example
* ```
* // Generate dates for each day in May 2025
* const datesInMay = ChronoUtilzHelper.generateDateRange({
* start: '2025-05-01',
* end: '2025-05-31'
* });
* ```
*
* @param options - Configuration options for the date range
* @returns An array of Date objects
*/
declare function generateDateRange(options: DateRangeOptions): Date[];
/**
* Gets a human-readable duration string from milliseconds
*
* @example
* ```
* // "2 days, 4 hours, 30 minutes"
* const duration = ChronoUtilzHelper.formatDuration(189000000);
* ```
*
* @param milliseconds - The duration in milliseconds
* @param options - Formatting options
* @returns A formatted duration string
*/
declare function formatDuration(milliseconds: number, options?: {
longFormat?: boolean;
maxUnits?: number;
}): string;
/**
* Returns the quarter number (1-4) for a given date
*
* @example
* ```
* const quarter = ChronoUtilzHelper.getQuarter(new Date(2025, 4, 15)); // 2 (Q2)
* ```
*
* @param date - The date to get the quarter for
* @returns The quarter number (1-4)
*/
declare function getQuarter(date: Date | string): number;
/**
* Returns the first or last date of a quarter
*
* @example
* ```
* // Get the first day of the current quarter
* const startOfQuarter = ChronoUtilzHelper.getQuarterDate(new Date(), 'start');
*
* // Get the last day of Q3 2025
* const endOfQ3 = ChronoUtilzHelper.getQuarterDate(new Date(2025, 8, 15), 'end');
* ```
*
* @param date - The reference date
* @param type - Either 'start' or 'end' of the quarter
* @returns Date object representing the start or end of the quarter
*/
declare function getQuarterDate(date: Date | string, type: 'start' | 'end'): Date;
/**
* Calculates business days between two dates (excluding weekends and optionally holidays)
*
* @example
* ```
* // Calculate business days between two dates
* const workDays = ChronoUtilzHelper.getBusinessDays(
* '2025-05-01',
* '2025-05-15',
* ['2025-05-05'] // Optional holidays to exclude
* );
* ```
*
* @param startDate - Start date
* @param endDate - End date
* @param holidays - Optional array of holiday dates to exclude
* @returns Number of business days between dates
*/
declare function getBusinessDays(startDate: Date | string, endDate: Date | string, holidays?: (Date | string)[]): number;
/**
* Age calculator that handles leap years and different formats
*
* @example
* ```
* // Calculate age in years
* const age = ChronoUtilzHelper.calculateAge('1990-05-15'); // 35 (in 2025)
*
* // Calculate age in multiple units
* const detailedAge = ChronoUtilzHelper.calculateAge('1990-05-15', {
* units: ['year', 'month', 'day']
* }); // { years: 35, months: 0, days: 23 } (if today is May 7, 2025)
* ```
*
* @param birthDate - The birth date
* @param options - Calculation options
* @returns Age in years or detailed object with multiple units
*/
declare function calculateAge(birthDate: Date | string, options?: {
referenceDate?: Date | string;
units?: ('year' | 'month' | 'day')[];
}): number | {
years: number;
months: number;
days: number;
};
/**
* Creates a deep copy of a Date object
* @param date - The date to clone
* @returns A new Date object with the same time value
*/
declare function cloneDate(date: Date | string | number): Date;
/**
* Returns the earliest date from an array of dates
* @param dates - Array of dates to compare
* @returns The earliest date
*/
declare function minDate(...dates: (Date | string | number)[]): Date;
/**
* Returns the latest date from an array of dates
* @param dates - Array of dates to compare
* @returns The latest date
*/
declare function maxDate(...dates: (Date | string | number)[]): Date;
/**
* Rounds a date to the nearest specified unit
* @param date - The date to round
* @param unit - The time unit to round to
* @returns A new Date rounded to the nearest unit
*/
declare function roundToNearest(date: Date | string | number, unit: Extract<TimeUnit, 'minute' | 'hour' | 'day'>): Date;
/**
* Compares two dates and returns -1, 0, or 1
* @param date1 - First date
* @param date2 - Second date
* @param unit - Optional time unit for comparison precision
* @returns -1 if date1 < date2, 0 if equal, 1 if date1 > date2
*/
declare function compareDates(date1: Date | string | number, date2: Date | string | number, unit?: TimeUnit): -1 | 0 | 1;
/**
* Gets the Unix timestamp for a date
* @param date - The date to convert
* @param inSeconds - Whether to return timestamp in seconds (default: false, returns milliseconds)
* @returns Unix timestamp
*/
declare function getTimestamp(date: Date | string | number, inSeconds?: boolean): number;
/**
* Creates a Date from a Unix timestamp
* @param timestamp - Unix timestamp in milliseconds or seconds
* @returns A new Date object
*/
declare function fromTimestamp(timestamp: number): Date;
/**
* Generates a random date between two dates
* @param startDate - The start of the range
* @param endDate - The end of the range
* @returns A random Date within the specified range
*/
declare function randomDate(startDate: Date | string | number, endDate: Date | string | number): Date;
/**
* Copies the time portion (hours, minutes, seconds, milliseconds) from one date to another
* @param fromDate - The date to copy time from
* @param toDate - The date to copy time to
* @returns A new Date with the date from toDate and time from fromDate
*/
declare function copyTime(fromDate: Date | string | number, toDate: Date | string | number): Date;
/**
* Truncates a date to the specified unit (sets smaller units to their minimum values)
* @param date - The date to truncate
* @param unit - The time unit to truncate to
* @returns A new Date truncated to the specified unit
*/
declare function truncateToUnit(date: Date | string | number, unit: TimeUnit): Date;
/**
* Sets the time components of a date
* @param date - The base date
* @param hours - Hours (0-23)
* @param minutes - Minutes (0-59), optional
* @param seconds - Seconds (0-59), optional
* @param milliseconds - Milliseconds (0-999), optional
* @returns A new Date with the specified time components
*/
declare function setTime(date: Date | string | number, hours: number, minutes?: number, seconds?: number, milliseconds?: number): Date;
/**
* Checks if two dates fall on the same day
* @param date1 - First date to compare
* @param date2 - Second date to compare
* @returns True if both dates are on the same day
*/
declare function isSameDay(date1: Date | string | number, date2: Date | string | number): boolean;
/**
* Checks if two dates fall in the same week (Sunday-Saturday)
* @param date1 - First date to compare
* @param date2 - Second date to compare
* @returns True if both dates are in the same week
*/
declare function isSameWeek(date1: Date | string | number, date2: Date | string | number): boolean;
/**
* Checks if two dates fall in the same month and year
* @param date1 - First date to compare
* @param date2 - Second date to compare
* @returns True if both dates are in the same month and year
*/
declare function isSameMonth(date1: Date | string | number, date2: Date | string | number): boolean;
/**
* Checks if two dates fall in the same year
* @param date1 - First date to compare
* @param date2 - Second date to compare
* @returns True if both dates are in the same year
*/
declare function isSameYear(date1: Date | string | number, date2: Date | string | number): boolean;
/**
* Checks if the first date is after the second date
* @param date1 - First date to compare
* @param date2 - Second date to compare
* @param unit - Optional time unit for comparison precision
* @returns True if date1 is after date2
*/
declare function isAfter(date1: Date | string | number, date2: Date | string | number, unit?: TimeUnit): boolean;
/**
* Checks if the first date is before the second date
* @param date1 - First date to compare
* @param date2 - Second date to compare
* @param unit - Optional time unit for comparison precision
* @returns True if date1 is before date2
*/
declare function isBefore(date1: Date | string | number, date2: Date | string | number, unit?: TimeUnit): boolean;
/**
* Checks if a date falls within a specified range
* @param date - The date to check
* @param startDate - The start of the range
* @param endDate - The end of the range
* @param inclusive - Whether to include the boundaries (default: true)
* @returns True if the date is within the specified range
*/
declare function isWithinRange(date: Date | string | number, startDate: Date | string | number, endDate: Date | string | number, inclusive?: boolean): boolean;
/**
* Validates if a date range is valid (start date is before or equal to end date)
* @param startDate - The start date of the range
* @param endDate - The end date of the range
* @returns True if the range is valid
*/
declare function isValidRange(startDate: Date | string | number, endDate: Date | string | number): boolean;
/**
* Sort order for date arrays
*/
type SortOrder = 'asc' | 'desc';
/**
* Sorts an array of dates in ascending or descending order
* @param dateArray - Array of dates to sort
* @param order - Sort order ('asc' for ascending, 'desc' for descending)
* @returns A new sorted array of Date objects
*/
declare function sortDates(dateArray: (Date | string | number)[], order?: SortOrder): Date[];
/**
* Gets the earliest date from an array of dates
* @param dateArray - Array of dates to compare
* @returns The earliest date as a new Date object
*/
declare function getEarliestDate(dateArray: (Date | string | number)[]): Date;
/**
* Gets the latest date from an array of dates
* @param dateArray - Array of dates to compare
* @returns The latest date as a new Date object
*/
declare function getLatestDate(dateArray: (Date | string | number)[]): Date;
/**
* Removes duplicate dates from an array (based on day precision)
* @param dateArray - Array of dates that may contain duplicates
* @param unit - Time unit for comparison precision (default: 'day')
* @returns A new array with duplicate dates removed
*/
declare function removeDuplicateDates(dateArray: (Date | string | number)[], unit?: TimeUnit): Date[];
/**
* Checks if the given date is the first day of the month
* @param date - The date to check
* @returns True if it's the first day of the month
*
* @example
* ```typescript
* isFirstDayOfMonth(new Date('2024-01-01')) // true
* isFirstDayOfMonth(new Date('2024-01-15')) // false
* ```
*/
declare function isFirstDayOfMonth(date: Date | string | number): boolean;
/**
* Checks if the given date is the last day of the month
* @param date - The date to check
* @returns True if it's the last day of the month
*
* @example
* ```typescript
* isLastDayOfMonth(new Date('2024-01-31')) // true
* isLastDayOfMonth(new Date('2024-02-29')) // true (leap year)
* isLastDayOfMonth(new Date('2024-01-15')) // false
* ```
*/
declare function isLastDayOfMonth(date: Date | string | number): boolean;
/**
* Checks if the given date is the first day of the year (January 1st)
* @param date - The date to check
* @returns True if it's January 1st
*
* @example
* ```typescript
* isFirstDayOfYear(new Date('2024-01-01')) // true
* isFirstDayOfYear(new Date('2024-12-31')) // false
* ```
*/
declare function isFirstDayOfYear(date: Date | string | number): boolean;
/**
* Checks if the given date is the last day of the year (December 31st)
* @param date - The date to check
* @returns True if it's December 31st
*
* @example
* ```typescript
* isLastDayOfYear(new Date('2024-12-31')) // true
* isLastDayOfYear(new Date('2024-01-01')) // false
* ```
*/
declare function isLastDayOfYear(date: Date | string | number): boolean;
/**
* Week boundaries result interface
*/
interface WeekBoundaries {
/** Start of the week */
start: Date;
/** End of the week */
end: Date;
}
/**
* Gets the start and end dates of the week containing the given date
* @param date - The date to find week boundaries for
* @param weekStartsOn - Day of week that starts the week (0=Sunday, 1=Monday, etc.)
* @returns Object with 'start' and 'end' Date properties
*
* @example
* ```typescript
* // For a date in mid-week (Monday start)
* getWeekBoundaries(new Date('2024-01-15'))
* // Returns: { start: Monday date, end: Sunday date }
*
* // Sunday start week
* getWeekBoundaries(new Date('2024-01-15'), 0)
* // Returns: { start: Sunday date, end: Saturday date }
* ```
*/
declare function getWeekBoundaries(date: Date | string | number, weekStartsOn?: number): WeekBoundaries;
/**
* Month boundaries result interface
*/
interface MonthBoundaries {
/** Start of the month */
start: Date;
/** End of the month */
end: Date;
}
/**
* Gets the start and end dates of the month containing the given date
* @param date - The date to find month boundaries for
* @returns Object with 'start' and 'end' Date properties
*
* @example
* ```typescript
* getMonthBoundaries(new Date('2024-01-15'))
* // Returns: { start: 2024-01-01 00:00:00, end: 2024-01-31 23:59:59 }
*
* getMonthBoundaries(new Date('2024-02-15'))
* // Returns: { start: 2024-02-01 00:00:00, end: 2024-02-29 23:59:59 } (leap year)
* ```
*/
declare function getMonthBoundaries(date: Date | string | number): MonthBoundaries;
/**
* Year boundaries result interface
*/
interface YearBoundaries {
/** Start of the year */
start: Date;
/** End of the year */
end: Date;
}
/**
* Gets the start and end dates of the specified year
* @param year - The year to get boundaries for
* @returns Object with 'start' and 'end' Date properties
*
* @example
* ```typescript
* getYearBoundaries(2024)
* // Returns: { start: 2024-01-01 00:00:00, end: 2024-12-31 23:59:59 }
* ```
*/
declare function getYearBoundaries(year: number): YearBoundaries;
/**
* Quarter boundaries result interface
*/
interface QuarterBoundaries {
/** Start of the quarter */
start: Date;
/** End of the quarter */
end: Date;
}
/**
* Gets the start and end dates of the specified quarter in the given year
* @param year - The year
* @param quarter - The quarter (1, 2, 3, or 4)
* @returns Object with 'start' and 'end' Date properties
*
* @example
* ```typescript
* getQuarterBoundaries(2024, 1)
* // Returns: { start: 2024-01-01 00:00:00, end: 2024-03-31 23:59:59 }
*
* getQuarterBoundaries(2024, 4)
* // Returns: { start: 2024-10-01 00:00:00, end: 2024-12-31 23:59:59 }
* ```
*/
declare function getQuarterBoundaries(year: number, quarter: number): QuarterBoundaries;
/**
* Returns a new date with time set to midnight (00:00:00.000)
* @param date - The date to strip time from
* @returns New date at midnight
*
* @example
* ```typescript
* stripTime(new Date('2024-01-15 14:30:45'))
* // Returns: 2024-01-15 00:00:00.000
* ```
*/
declare function stripTime(date: Date | string | number): Date;
/**
* Returns a new date set to midnight (00:00:00.000) of the given date
* Alias for stripTime() for semantic clarity
* @param date - The date to set to midnight
* @returns New date at midnight
*
* @example
* ```typescript
* getMidnight(new Date('2024-01-15 14:30:45'))
* // Returns: 2024-01-15 00:00:00.000
* ```
*/
declare function getMidnight(date: Date | string | number): Date;
/**
* Returns a new date set to noon (12:00:00.000) of the given date
* @param date - The date to set to noon
* @returns New date at noon
*
* @example
* ```typescript
* getNoon(new Date('2024-01-15 14:30:45'))
* // Returns: 2024-01-15 12:00:00.000
* ```
*/
declare function getNoon(date: Date | string | number): Date;
/**
* Global configuration for working days and holidays
*/
interface BusinessDayConfig {
/** Working days (0=Sunday, 1=Monday, ..., 6=Saturday) */
workingDays: number[];
/** Array of holiday dates (ISO strings or Date objects) */
holidays: Set<string>;
}
/**
* Configures which days of the week are considered working days
* @param dayArray - Array of day numbers (0=Sunday, 1=Monday, ..., 6=Saturday)
* @returns The updated configuration for method chaining
*
* @example
* ```typescript
* // Standard Monday-Friday
* configureWorkingDays([1, 2, 3, 4, 5])
*
* // Sunday-Thursday (Middle East style)
* configureWorkingDays([0, 1, 2, 3, 4])
*
* // Monday-Saturday
* configureWorkingDays([1, 2, 3, 4, 5, 6])
* ```
*/
declare function configureWorkingDays(dayArray: number[]): BusinessDayConfig;
/**
* Adds holidays to the business day configuration
* @param holidays - Array of holiday dates
* @returns The updated configuration for method chaining
*
* @example
* ```typescript
* configureHolidays([
* '2024-01-01', // New Year's Day
* '2024-07-04', // Independence Day
* '2024-12-25' // Christmas Day
* ])
* ```
*/
declare function configureHolidays(holidays: (Date | string | number)[]): BusinessDayConfig;
/**
* Gets the current business day configuration
* @returns A copy of the current configuration
*/
declare function getBusinessDayConfig(): BusinessDayConfig;
/**
* Resets business day configuration to defaults
* @returns The reset configuration
*/
declare function resetBusinessDayConfig(): BusinessDayConfig;
/**
* Checks if a date falls on a weekend
* @param date - The date to check
* @returns True if the date is a weekend
*
* @example
* ```typescript
* isWeekend(new Date('2024-01-06')) // true (Saturday)
* isWeekend(new Date('2024-01-08')) // false (Monday)
* ```
*/
declare function isWeekend(date: Date | string | number): boolean;
/**
* Checks if a date falls on a weekday (according to current working day configuration)
* @param date - The date to check
* @returns True if the date is a weekday
*
* @example
* ```typescript
* isWeekday(new Date('2024-01-08')) // true (Monday)
* isWeekday(new Date('2024-01-06')) // false (Saturday)
* ```
*/
declare function isWeekday(date: Date | string | number): boolean;
/**
* Checks if a date is a business day (weekday and not a holiday)
* @param date - The date to check
* @returns True if the date is a business day
*
* @example
* ```typescript
* isBusinessDay(new Date('2024-01-08')) // true (Monday, not holiday)
* isBusinessDay(new Date('2024-01-01')) // false (New Year's Day)
* isBusinessDay(new Date('2024-01-06')) // false (Saturday)
* ```
*/
declare function isBusinessDay(date: Date | string | number): boolean;
/**
* Adds the specified number of business days to a date
* @param date - The starting date
* @param businessDays - Number of business days to add
* @returns A new date with business days added
*
* @example
* ```typescript
* // Add 5 business days to Friday, Jan 5, 2024
* addBusinessDays(new Date('2024-01-05'), 5)
* // Returns: Friday, Jan 12, 2024 (skips weekends)
* ```
*/
declare function addBusinessDays(date: Date | string | number, businessDays: number, timezone?: IANATimezone): Date;
/**
* Subtracts the specified number of business days from a date
* @param date - The starting date
* @param businessDays - Number of business days to subtract
* @returns A new date with business days subtracted
*
* @example
* ```typescript
* // Subtract 3 business days from Wednesday, Jan 10, 2024
* subtractBusinessDays(new Date('2024-01-10'), 3)
* // Returns: Friday, Jan 5, 2024 (skips weekend)
* ```
*/
declare function subtractBusinessDays(date: Date | string | number, businessDays: number): Date;
/**
* Gets the next business day from the given date
* @param date - The starting date
* @returns The next business day
*
* @example
* ```typescript
* // From Friday, Jan 5, 2024
* getNextBusinessDay(new Date('2024-01-05'))
* // Returns: Monday, Jan 8, 2024
* ```
*/
declare function getNextBusinessDay(date: Date | string | number): Date;
/**
* Gets the previous business day from the given date
* @param date - The starting date
* @returns The previous business day
*
* @example
* ```typescript
* // From Monday, Jan 8, 2024
* getPreviousBusinessDay(new Date('2024-01-08'))
* // Returns: Friday, Jan 5, 2024
* ```
*/
declare function getPreviousBusinessDay(date: Date | string | number): Date;
/**
* Counts the number of business days in a given month
* @param year - The year
* @param month - The month (1-12)
* @returns Number of business days in the month
*
* @example
* ```typescript
* businessDaysInMonth(2024, 1) // Returns: 23 (January 2024)
* businessDaysInMonth(2024, 12) // Returns: 22 (December 2024)
* ```
*/
declare function businessDaysInMonth(year: number, month: number): number;
/**
* Calculates the difference in business days between two dates
* @param startDate - The start date
* @param endDate - The end date
* @returns Number of business days between the dates (positive if endDate > startDate)
*
* @example
* ```typescript
* // From Monday to Friday (same week)
* differenceInBusinessDays(
* new Date('2024-01-08'),
* new Date('2024-01-12')
* ) // Returns: 4
*
* // Across weekends
* differenceInBusinessDays(
* new Date('2024-01-05'), // Friday
* new Date('2024-01-09') // Tuesday
* ) // Returns: 2 (excludes weekend)
* ```
*/
declare function differenceInBusinessDays(startDate: Date | string | number, endDate: Date | string | number): number;
/**
* Checks if a date is the last business day of the month
* @param date - The date to check
* @returns True if it's the last business day of the month
*
* @example
* ```typescript
* isLastBusinessDayOfMonth(new Date('2024-01-31')) // true if Jan 31 is a business day
* isLastBusinessDayOfMonth(new Date('2024-01-30')) // true if Jan 31 is weekend/holiday
* ```
*/
declare function isLastBusinessDayOfMonth(date: Date | string | number): boolean;
/**
* Checks if a date is the first business day of the month
* @param date - The date to check
* @returns True if it's the first business day of the month
*
* @example
* ```typescript
* isFirstBusinessDayOfMonth(new Date('2024-01-01')) // true if Jan 1 is a business day
* isFirstBusinessDayOfMonth(new Date('2024-01-02')) // true if Jan 1 is weekend/holiday
* ```
*/
declare function isFirstBusinessDayOfMonth(date: Date | string | number): boolean;
/**
* Gets an array of all business days in a given month
* @param year - The year
* @param month - The month (1-12)
* @returns Array of Date objects representing business days
*
* @example
* ```typescript
* getBusinessDaysInMonth(2024, 1)
* // Returns: Array of Date objects for all business days in January 2024
* ```
*/
declare function getBusinessDaysInMonth(year: number, month: number): Date[];
/**
* Holiday configuration interface
*/
interface HolidayRule {
name: string;
date: string | ((year: number) => Date);
type?: 'fixed' | 'floating';
}
/**
* Checks if a date is a holiday
* @param date - The date to check
* @param holidaysList - Optional custom list of holidays
* @returns True if the date is a holiday
*/
declare function isHoliday(date: Date | string | number, holidaysList?: (Date | string)[], timezone?: IANATimezone): boolean;
/**
* Gets holidays for a specific year and country
* @param year - The year to get holidays for
* @param country - Optional country code (default: 'US')
* @returns Array of holiday dates
*/
declare function getHolidays(year: number, country?: string): Date[];
/**
* Adds holiday rules for a country
* @param country - The country code
* @param rules - Array of holiday rules
*/
declare function addHolidayRules(country: string, rules: HolidayRule[]): void;
/**
* Gets the next holiday from a given date
* @param date - The starting date
* @param country - Optional country code (default: 'US')
* @returns The next holiday date
*/
declare function getNextHoliday(date: Date | string | number, country?: string): Date | null;
/**
* Adds custom holidays
* @param holidayArray - Array of custom holiday dates
*/
declare function addCustomHolidays(holidayArray: (Date | string | number)[]): void;
/**
* Custom business day rules interface
*/
interface BusinessDayRules {
workingDays: number[];
holidays: (Date | string)[];
workingHours?: {
start: string;
end: string;
};
}
/**
* Calculates business days with custom rules
* @param start - Start date
* @param end - End date
* @param rules - Custom business day rules
* @returns Number of business days
*/
declare function calculateBusinessDaysCustom(start: Date | string | number, end: Date | string | number, rules: BusinessDayRules): number;
/**
* Working hours schedule interface
*/
interface WorkingSchedule {
start: string;
end: string;
days?: number[];
}
/**
* Gets working hours between two dates
* @param start - Start date/time
* @param end - End date/time
* @param workingHours - Working hours schedule
* @returns Number of working hours
*/
declare function getWorkingHoursBetween(start: Date | string | number, end: Date | string | number, workingHours: WorkingSchedule): number;
/**
* Adds working hours to a date
* @param date - Starting date
* @param hours - Hours to add
* @param schedule - Optional working schedule
* @returns New date with working hours added
*/
declare function addWorkingHours(date: Date | string | number, hours: number, schedule?: WorkingSchedule): Date;
/**
* Checks if a date/time is within working hours
* @param date - The date/time to check
* @param schedule - Optional working schedule
* @returns True if within working hours
*/
declare function isWorkingHours(date: Date | string | number, schedule?: WorkingSchedule): boolean;
/**
* Gets the next working hour from a given date
* @param date - Starting date
* @param schedule - Optional working schedule
* @returns Next working hour date
*/
declare function getNextWorkingHour(date: Date | string | number, schedule?: WorkingSchedule): Date;
/**
* Merges a date part with a time part
* @param datePart - The date component
* @param timePart - The time component
* @returns New date with merged date and time
*/
declare function mergeDateTime(datePart: Date | string | number, timePart: Date | string | number): Date;
/**
* Time of day categories
*/
type TimeOfDay = 'Night' | 'Morning' | 'Afternoon' | 'Evening';
/**
* Gets the time of day category
* @param date - The date to categorize
* @returns Time of day category
*/
declare function timeOfDay(date: Date | string | number): TimeOfDay;
/**
* Gets ISO week number (ISO-8601 standard)
* @param date - The date
* @returns ISO week number
*/
declare function getISOWeek(date: Date | string | number): number;
/**
* Gets the week number within a month
* @param date - The date
* @returns Week number within the month (1-6)
*/
declare function getWeekOfMonth(date: Date | string | number): number;
/**
* Gets fiscal quarter
* @param date - The date
* @param fiscalYearStart - Fiscal year start month (1-12, default: 1 for January)
* @returns Fiscal quarter (1-4)
*/
declare function getFiscalQuarter(date: Date | string | number, fiscalYearStart?: number): number;
/**
* Gets fiscal year
* @param date - The date
* @param fiscalYearStart - Fiscal year start month (1-12, default: 1 for January)
* @returns Fiscal year
*/
declare function getFiscalYear(date: Date | string | number, fiscalYearStart?: number): number;
/**
* Pay period frequencies
*/
type PayPeriodFrequency = 'weekly' | 'bi-weekly' | 'semi-monthly' | 'monthly';
/**
* Gets pay periods between dates
* @param startDate - Start date
* @param endDate - End date
* @param frequency - Pay period frequency
* @returns Array of pay period start dates
*/
declare function getPayPeriods(startDate: Date | string | number, endDate: Date | string | number, frequency: PayPeriodFrequency): Date[];
/**
* Hemispheres for season calculation
*/
type Hemisphere = 'northern' | 'southern';
/**
* Season types
*/
type Season = 'Spring' | 'Summer' | 'Autumn' | 'Winter';
/**
* Gets the season for a date
* @param date - The date
* @param hemisphere - Northern or southern hemisphere (default: 'northern')
* @returns Season name
*/
declare function getSeason(date: Date | string | number, hemisphere?: Hemisphere): Season;
/**
* Month name formats
*/
type MonthNameFormat = 'long' | 'short' | 'narrow';
/**
* Gets month name
* @param monthNumber - Month number (1-12)
* @param locale - Locale string (default: 'en-US')
* @param format - Format type (default: 'long')
* @returns Month name
*/
declare function getMonthName(monthNumber: number, locale?: string, format?: MonthNameFormat): string;
/**
* Gets detailed information about months in a quarter
* @param quarter - Quarter number (1-4)
* @param year - Year
* @returns Object containing quarter info and months
*/
declare function getMonthsInQuarter(quarter: number, year: number): {
quarter: number;
year: number;
months: {
name: string;
number: number;
firstDay: Date;
lastDay: Date;
}[];
startDate: Date;
endDate: Date;
};
/**
* Gets the next occurrence of a specific day of week
* @param date - Starting date
* @param dayOfWeek - Day of week (0=Sunday, 1=Monday, etc.)
* @returns Next occurrence date
*/
declare function nextOccurrence(date: Date | string | number, dayOfWeek: number): Date;
/**
* Gets the previous occurrence of a specific day of week
* @param date - Starting date
* @param dayOfWeek - Day of week (0=Sunday, 1=Monday, etc.)
* @returns Previous occurrence date
*/
declare function previousOccurrence(date: Date | string | number, dayOfWeek: number): Date;
/**
* Converts a date to a different timezone using IANA timezone identifiers
* @param date - The date to convert
* @param options - Timezone conversion options
* @returns Date object in the target timezone
* @example
* ```javascript
* const utcDate = new Date('2025-01-15T12:00:00Z');
* const nyTime = convertTimezone(utcDate, {
* from: 'UTC',
* to: 'America/New_York'
* });
* // Returns: 2025-01-15T07:00:00-05:00 (EST)
* ```
*/
declare function convertTimezone(date: Date | string | number, options: TimezoneConversionOptions): Date;
/**
* Parses natural language time expressions into dates
* @param expression - Natural language expression
* @param options - Parsing options
* @returns Parsed date or null if invalid
* @example
* ```javascript
* const tomorrow = parseNaturalLanguage('tomorrow');
* // Returns: Date object for tomorrow at 00:00:00
*
* const nextFriday = parseNaturalLanguage('next friday');
* // Returns: Date object for next Friday at 00:00:00
*
* const inTwoWeeks = parseNaturalLanguage('in 2 weeks');
* // Returns: Date object 14 days from now
*
* const threeDaysAgo = parseNaturalLanguage('3 days ago');
* // Returns: Date object 3 days before now
* ```
*/
declare function parseNaturalLanguage(expression: NaturalTimeExpression, options?: NaturalLanguageOptions): Date | null;
/**
* Generates recurring dates based on a pattern
* @param startDate - Starting date
* @param config - Recurring configuration
* @returns Array of dates matching the pattern
* @example
* ```javascript
* const weeklyMeetings = generateRecurringDates('2025-01-06', {
* pattern: 'weekly',
* maxOccurrences: 10
* });
* // Returns: [2025-01-06, 2025-01-13, 2025-01-20, ...]
*
* const monthlyReports = generateRecurringDates('2025-01-01', {
* pattern: 'monthly',
* maxOccurrences: 12,
* endDate: new Date('2025-12-31')
* });
* // Returns: First day of each month for 2025
* ```
*/
declare function generateRecurringDates(startDate: Date | string | number, config: RecurringConfig): Date[];
/**
* Performs comprehensive date comparison
* @param date1 - First date
* @param date2 - Second date
* @returns Detailed comparison result
*/
declare function compareDetailed(date1: Date | string | number, date2: Date | string | number): DateComparison;
/**
* Calculates the duration between two dates with advanced options
* @param startDate - Start date
* @param endDate - End date
* @param options - Display options
* @returns Formatted duration string
*/
declare function calculateAdvancedDuration(startDate: Date | string | number, endDate: Date | string | number, options?: DurationDisplayOptions): string;
/**
* Gets the nth occurrence of a weekday in a month
* @param year - Year
* @param month - Month (1-12)
* @param dayOfWeek - Day of week (0-6, Sunday is 0)
* @param occu