UNPKG

@catbee/utils

Version:

A modular, production-grade utility toolkit for Node.js and TypeScript, designed for robust, scalable applications (including Express-based services). All utilities are tree-shakable and can be imported independently.

700 lines (696 loc) 20.6 kB
/* * The MIT License * * Copyright (c) 2026 Catbee Technologies. https://catbee.in/license * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Format options for the formatDate function */ interface DateFormatOptions { /** Date format pattern (default: 'yyyy-MM-dd') */ format?: string; /** Locale to use for formatting (default: system locale) */ locale?: string | string[]; /** Time zone to use (default: system time zone) */ timeZone?: string; } /** * Format a date according to the specified format pattern. * * @param date - Date to format * @param options - Formatting options * @returns Formatted date string * * @example * ```typescript * // Format as ISO date * formatDate(new Date(), { format: 'yyyy-MM-dd' }); // '2023-05-15' * * // Format with time * formatDate(new Date(), { format: 'yyyy-MM-dd HH:mm:ss' }); // '2023-05-15 14:30:22' * * // Format with locale * formatDate(new Date(), { format: 'PPPP', locale: 'fr-FR' }); // 'lundi 15 mai 2023' * ``` */ declare function formatDate(date: Date | number, options?: DateFormatOptions): string; /** * Format a date as relative time (e.g., "5 minutes ago", "in 3 days"). * * @param date - Date to format * @param now - Reference date (default: current time) * @param locale - Locale to use for formatting * @returns Formatted relative time string */ declare function formatRelativeTime(date: Date | number, now?: Date | number, locale?: string | string[]): string; /** * Parse a date string or timestamp into a Date object. * * @param input - Date string or timestamp to parse * @param fallback - Fallback date if parsing fails * @returns Parsed Date object or fallback * * @example * ```typescript * parseDate('2023-05-15'); // Date object for May 15, 2023 * parseDate('invalid', new Date()); // Returns current date as fallback * ``` */ declare function parseDate(input: string | number, fallback?: Date): Date | null; /** * Calculate the difference between two dates in the specified unit. * * @param date1 - First date * @param date2 - Second date (default: current time) * @param unit - Unit of time for the difference * @returns Difference in the specified unit * * @example * ```typescript * // Get difference in days * dateDiff(new Date('2023-05-15'), new Date('2023-05-10'), 'days'); // 5 * * // Get difference in hours * dateDiff(new Date('2023-05-15T10:00:00'), new Date('2023-05-15T06:00:00'), 'hours'); // 4 * ``` */ declare function dateDiff(date1: Date | number, date2?: Date | number, unit?: 'milliseconds' | 'seconds' | 'minutes' | 'hours' | 'days' | 'months' | 'years'): number; /** * Add a specified amount of time to a date. * * @param date - Base date * @param amount - Amount to add (can be negative) * @param unit - Unit of time to add * @returns New date with the addition * * @example * ```typescript * // Add 5 days * addToDate(new Date('2023-05-15'), 5, 'days'); // Date for May 20, 2023 * * // Subtract 2 hours * addToDate(new Date('2023-05-15T10:00:00'), -2, 'hours'); // Date for May 15, 2023 08:00:00 * ``` */ declare function addToDate(date: Date | number, amount: number, unit: 'milliseconds' | 'seconds' | 'minutes' | 'hours' | 'days' | 'months' | 'years'): Date; /** * Get the start of a time period containing the specified date. * * @param date - Date to get the start from * @param unit - Time unit * @returns Date object representing the start of the time unit * * @example * ```typescript * // Get start of day (midnight) * startOf(new Date('2023-05-15T14:30:00'), 'day'); // Date for May 15, 2023 00:00:00 * * // Get start of month * startOf(new Date('2023-05-15'), 'month'); // Date for May 1, 2023 * ``` */ declare function startOf(date: Date | number, unit: 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year'): Date; /** * Get the end of a time period containing the specified date. * * @param date - Date to get the end from * @param unit - Time unit * @returns Date object representing the end of the time unit * * @example * ```typescript * // Get end of day (23:59:59.999) * endOf(new Date('2023-05-15T14:30:00'), 'day'); // Date for May 15, 2023 23:59:59.999 * * // Get end of month * endOf(new Date('2023-05-15'), 'month'); // Date for May 31, 2023 23:59:59.999 * ``` */ declare function endOf(date: Date | number, unit: 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year'): Date; /** * Check if a date is between two other dates. * * @param date - Date to check * @param start - Start date of the range * @param end - End date of the range * @param inclusive - Whether the comparison should be inclusive of start/end * @returns True if the date is within the range * * @example * ```typescript * const date = new Date('2023-05-15'); * const start = new Date('2023-05-10'); * const end = new Date('2023-05-20'); * * isBetween(date, start, end); // true * ``` */ declare function isBetween(date: Date | number, start: Date | number, end: Date | number, inclusive?: boolean): boolean; /** * Check if a year is a leap year. * * @param year - Year to check (or date object) * @returns True if the year is a leap year */ declare function isLeapYear(year: number | Date): boolean; /** * Get the number of days in a month. * * @param year - Year * @param month - Month (0-11) * @returns Number of days in the month */ declare function daysInMonth(year: number | Date, month?: number): number; /** * Format a duration given in milliseconds to a human readable string. * Examples: 3661000 -> "1h 1m 1s", 90061 -> "1m 30s 61ms" * * @param {number} ms - Duration in milliseconds * @returns {string} Human readable duration */ declare function formatDuration(ms: number): string; /** * Parse a duration string or number into milliseconds. * Supports formats like: 1y, 2w, 3d, 4h, 5m, 6s, 7ms, 1w2d3h, or plain milliseconds like "60000" * * @param value - Duration string or number * @returns Milliseconds */ declare function parseDuration(value: string | number): number; /** * Convert a duration string into a Date object representing the future time. * * @param input - Duration string (e.g., "5m", "2h", "1d") * @returns Date object representing the future time * * @example * ```typescript * toDateFromNow("5m"); // Date object 5 minutes from now * toDateFromNow("2h"); // Date object 2 hours from now * ``` */ declare function getDateFromDuration(input: string): Date; /** * Checks if a date is on a weekend (Saturday or Sunday). * * @param {Date | number} date - The date to check. * @returns {boolean} True if weekend. * * @example * isWeekend(new Date('2024-01-06')); // true (Saturday) */ declare function isWeekend(date: Date | number): boolean; /** * Checks if a date is today. * * @param {Date | number} date - The date to check. * @returns {boolean} True if today. * * @example * isToday(new Date()); // true */ declare function isToday(date: Date | number): boolean; /** * Checks if a date is in the future. * * @param {Date | number} date - The date to check. * @returns {boolean} True if in the future. * * @example * isFuture(new Date('2099-01-01')); // true */ declare function isFuture(date: Date | number): boolean; /** * Checks if a date is in the past. * * @param {Date | number} date - The date to check. * @returns {boolean} True if in the past. * * @example * isPast(new Date('2020-01-01')); // true */ declare function isPast(date: Date | number): boolean; /** * Adds days to a date. * * @param {Date | number} date - The base date. * @param {number} days - Number of days to add (can be negative). * @returns {Date} New date with days added. * * @example * addDays(new Date('2024-01-15'), 7); // 2024-01-22 */ declare function addDays(date: Date | number, days: number): Date; /** * Adds months to a date. * * @param {Date | number} date - The base date. * @param {number} months - Number of months to add (can be negative). * @returns {Date} New date with months added. * * @example * addMonths(new Date('2024-01-31'), 1); // 2024-02-29 (leap year) */ declare function addMonths(date: Date | number, months: number): Date; /** * Adds years to a date. * * @param {Date | number} date - The base date. * @param {number} years - Number of years to add (can be negative). * @returns {Date} New date with years added. * * @example * addYears(new Date('2024-01-15'), 5); // 2029-01-15 */ declare function addYears(date: Date | number, years: number): Date; /** * Gets the quarter of the year for a date (1-4). * * @param {Date | number} date - The date. * @returns {1 | 2 | 3 | 4} Quarter number. * * @example * quarterOf(new Date('2024-03-15')); // 1 * quarterOf(new Date('2024-07-15')); // 3 */ declare function quarterOf(date: Date | number): 1 | 2 | 3 | 4; /** * Gets the ISO week number of the year for a date. * * @param {Date | number} date - The date. * @returns {number} Week number (1-53). * * @example * weekOfYear(new Date('2024-01-15')); // 3 */ declare function weekOfYear(date: Date | number): number; /** * DateBuilder class for fluent date manipulation and building. * Provides a chainable API similar to Java's date builders. * All methods return a new instance, making it immutable. * * @example * ```typescript * // Create a date builder * const date = new DateBuilder() * .year(2024) * .month(5) * .day(15) * .hour(14) * .minute(30) * .build(); * * // Chain operations * const nextWeek = new DateBuilder() * .addDays(7) * .startOfDay() * .build(); * * // Use with existing date * const modified = DateBuilder.from(new Date()) * .addMonths(2) * .endOfMonth() * .format('yyyy-MM-dd'); * ``` */ declare class DateBuilder { private readonly date; /** * Creates a new DateBuilder instance. * @param date - Initial date (default: current date/time) */ constructor(date?: Date | number | string); /** * Create a DateBuilder from an existing date. * @param date - Date to build from */ static from(date: Date | number | string): DateBuilder; /** * Create a DateBuilder for the current moment. */ static now(): DateBuilder; /** * Create a DateBuilder for a specific date. * @param year - Year * @param month - Month (1-12, not 0-11) * @param day - Day of month * @param hour - Hour (default: 0) * @param minute - Minute (default: 0) * @param second - Second (default: 0) * @param millisecond - Millisecond (default: 0) */ static of(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number): DateBuilder; /** * Parse a date string into a DateBuilder. * @param dateString - Date string to parse */ static parse(dateString: string): DateBuilder; /** * Create a DateBuilder from a duration string (e.g., "5m", "2h", "1d" from now). * @param duration - Duration string */ static fromDuration(duration: string): DateBuilder; /** * Clone this DateBuilder instance. */ clone(): DateBuilder; /** * Set the year. * @param year - Year to set */ year(year: number): DateBuilder; /** * Set the month (1-12, not 0-11). * @param month - Month to set (1-12) */ month(month: number): DateBuilder; /** * Set the day of the month. * @param day - Day to set */ day(day: number): DateBuilder; /** * Set the hour. * @param hour - Hour to set */ hour(hour: number): DateBuilder; /** * Set the minute. * @param minute - Minute to set */ minute(minute: number): DateBuilder; /** * Set the second. * @param second - Second to set */ second(second: number): DateBuilder; /** * Set the millisecond. * @param millisecond - Millisecond to set */ millisecond(millisecond: number): DateBuilder; /** * Add years to the date. * @param years - Number of years to add (can be negative) */ addYears(years: number): DateBuilder; /** * Add months to the date. * @param months - Number of months to add (can be negative) */ addMonths(months: number): DateBuilder; /** * Add days to the date. * @param days - Number of days to add (can be negative) */ addDays(days: number): DateBuilder; /** * Add hours to the date. * @param hours - Number of hours to add (can be negative) */ addHours(hours: number): DateBuilder; /** * Add minutes to the date. * @param minutes - Number of minutes to add (can be negative) */ addMinutes(minutes: number): DateBuilder; /** * Add seconds to the date. * @param seconds - Number of seconds to add (can be negative) */ addSeconds(seconds: number): DateBuilder; /** * Add milliseconds to the date. * @param milliseconds - Number of milliseconds to add (can be negative) */ addMilliseconds(milliseconds: number): DateBuilder; /** * Subtract years from the date. * @param years - Number of years to subtract */ subtractYears(years: number): DateBuilder; /** * Subtract months from the date. * @param months - Number of months to subtract */ subtractMonths(months: number): DateBuilder; /** * Subtract days from the date. * @param days - Number of days to subtract */ subtractDays(days: number): DateBuilder; /** * Subtract hours from the date. * @param hours - Number of hours to subtract */ subtractHours(hours: number): DateBuilder; /** * Subtract minutes from the date. * @param minutes - Number of minutes to subtract */ subtractMinutes(minutes: number): DateBuilder; /** * Subtract seconds from the date. * @param seconds - Number of seconds to subtract */ subtractSeconds(seconds: number): DateBuilder; /** * Set to the start of the second. */ startOfSecond(): DateBuilder; /** * Set to the start of the minute. */ startOfMinute(): DateBuilder; /** * Set to the start of the hour. */ startOfHour(): DateBuilder; /** * Set to the start of the day (midnight). */ startOfDay(): DateBuilder; /** * Set to the start of the week (Sunday). */ startOfWeek(): DateBuilder; /** * Set to the start of the month. */ startOfMonth(): DateBuilder; /** * Set to the start of the quarter. */ startOfQuarter(): DateBuilder; /** * Set to the start of the year. */ startOfYear(): DateBuilder; /** * Set to the end of the second. */ endOfSecond(): DateBuilder; /** * Set to the end of the minute. */ endOfMinute(): DateBuilder; /** * Set to the end of the hour. */ endOfHour(): DateBuilder; /** * Set to the end of the day (23:59:59.999). */ endOfDay(): DateBuilder; /** * Set to the end of the week (Saturday). */ endOfWeek(): DateBuilder; /** * Set to the end of the month. */ endOfMonth(): DateBuilder; /** * Set to the end of the quarter. */ endOfQuarter(): DateBuilder; /** * Set to the end of the year. */ endOfYear(): DateBuilder; /** * Check if the date is before another date. * @param other - Date to compare with */ isBefore(other: Date | DateBuilder): boolean; /** * Check if the date is after another date. * @param other - Date to compare with */ isAfter(other: Date | DateBuilder): boolean; /** * Check if the date is the same as another date. * @param other - Date to compare with */ isSame(other: Date | DateBuilder): boolean; /** * Check if the date is between two dates. * @param start - Start date * @param end - End date * @param inclusive - Whether to include boundaries */ isBetween(start: Date | DateBuilder, end: Date | DateBuilder, inclusive?: boolean): boolean; /** * Check if the date is today. */ isToday(): boolean; /** * Check if the date is in the future. */ isFuture(): boolean; /** * Check if the date is in the past. */ isPast(): boolean; /** * Check if the date is on a weekend. */ isWeekend(): boolean; /** * Check if the year is a leap year. */ isLeapYear(): boolean; /** * Get the year. */ getYear(): number; /** * Get the month (1-12, not 0-11). */ getMonth(): number; /** * Get the day of the month. */ getDay(): number; /** * Get the day of the week (0-6, Sunday is 0). */ getDayOfWeek(): number; /** * Get the hour. */ getHour(): number; /** * Get the minute. */ getMinute(): number; /** * Get the second. */ getSecond(): number; /** * Get the millisecond. */ getMillisecond(): number; /** * Get the quarter (1-4). */ getQuarter(): 1 | 2 | 3 | 4; /** * Get the ISO week number. */ getWeekOfYear(): number; /** * Get the number of days in the current month. */ getDaysInMonth(): number; /** * Get the Unix timestamp in milliseconds. */ getTime(): number; /** * Get the Unix timestamp in seconds. */ getUnixTimestamp(): number; /** * Calculate the difference from another date. * @param other - Date to compare with * @param unit - Unit of time */ diff(other: Date | DateBuilder, unit?: 'milliseconds' | 'seconds' | 'minutes' | 'hours' | 'days' | 'months' | 'years'): number; /** * Get the difference from now. * @param unit - Unit of time */ diffFromNow(unit?: 'milliseconds' | 'seconds' | 'minutes' | 'hours' | 'days' | 'months' | 'years'): number; /** * Format the date. * @param options - Formatting options */ format(options?: DateFormatOptions | string): string; /** * Format as relative time (e.g., "5 minutes ago"). * @param locale - Locale for formatting */ formatRelative(locale?: string | string[]): string; /** * Format as ISO 8601 string. */ toISOString(): string; /** * Format as UTC string. */ toUTCString(): string; /** * Format as date string. */ toDateString(): string; /** * Format as time string. */ toTimeString(): string; /** * Format as locale string. */ toLocaleString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; /** * Convert to JSON string. */ toJSON(): string; /** * Build and return the Date object. */ build(): Date; /** * Get the Date object (alias for build). */ toDate(): Date; /** * Get the internal Date object value. */ valueOf(): number; /** * Convert to string. */ toString(): string; } export { DateBuilder, addDays, addMonths, addToDate, addYears, dateDiff, daysInMonth, endOf, formatDate, formatDuration, formatRelativeTime, getDateFromDuration, isBetween, isFuture, isLeapYear, isPast, isToday, isWeekend, parseDate, parseDuration, quarterOf, startOf, weekOfYear }; export type { DateFormatOptions };