UNPKG

@jlhv/date-helper

Version:

A simple date helper utility for different time formats.

235 lines (234 loc) 11.4 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getDSTOffsetInTimezone = exports.getDSTEndInTimezone = exports.getDSTStartInTimezone = exports.getDSTOffset = exports.getDSTEnd = exports.getDSTStart = exports.isDaylightSavingTime = exports.getTimezoneAbbreviation = exports.getTimezoneName = exports.getTimezoneOffset = exports.getCurrentDateInTimezone = exports.getYearsBetweenDates = exports.getMonthsBetweenDates = exports.getWeeksBetweenDates = exports.getDaysBetweenDates = exports.getLastDayOfMonth = exports.getFirstDayOfMonth = exports.getDaysInMonth = exports.isLeapYear = exports.subtractYears = exports.subtractMonths = exports.subtractWeeks = exports.subtractDays = exports.addYears = exports.addMonths = exports.addWeeks = exports.addDays = exports.getYear = exports.getMonthOfYear = exports.getDayOfWeek = exports.getCurrentDateString = exports.getCurrentDate = exports.getUTCDate = exports.getISODate = void 0; exports.formatDate = formatDate; const date_fns_1 = require("date-fns"); /** * Parses input into a Date object. */ function parseDate(date) { try { if (typeof date === "string") { const parsed = (0, date_fns_1.parseISO)(date); if (isNaN(parsed.getTime())) { throw new Error("Invalid date string"); } return parsed; } if (date instanceof Date && !isNaN(date.getTime())) { return date; } throw new Error("Invalid date"); } catch (error) { console.error("Error parsing date:", error); throw new Error("Invalid date format"); } } /** * Formats a date string. */ function formatDate(date = new Date(), formatStr = "yyyy-MM-dd HH:mm:ss") { try { const parsedDate = parseDate(date); if (isNaN(parsedDate.getTime())) { throw new Error("Invalid date"); } return (0, date_fns_1.format)(parsedDate, formatStr); } catch (error) { console.error("Error formatting date:", error); return "Invalid Date"; } } /** Date Retrieval Functions */ const getISODate = () => new Date().toISOString(); exports.getISODate = getISODate; const getUTCDate = () => new Date().toUTCString(); exports.getUTCDate = getUTCDate; const getCurrentDate = () => new Date(); exports.getCurrentDate = getCurrentDate; const getCurrentDateString = (formatStr = "yyyy-MM-dd HH:mm:ss") => formatDate(new Date(), formatStr); exports.getCurrentDateString = getCurrentDateString; /** Get Specific Parts of a Date */ const getDayOfWeek = (date = new Date()) => new Intl.DateTimeFormat("en-US", { weekday: "long" }).format(parseDate(date)); exports.getDayOfWeek = getDayOfWeek; const getMonthOfYear = (date = new Date()) => new Intl.DateTimeFormat("en-US", { month: "long" }).format(parseDate(date)); exports.getMonthOfYear = getMonthOfYear; const getYear = (date = new Date()) => parseDate(date).getFullYear(); exports.getYear = getYear; /** Arithmetic Operations */ const addDays = (date, days) => new Date(parseDate(date).getTime() + days * 86400000); exports.addDays = addDays; const addWeeks = (date, weeks) => (0, exports.addDays)(date, weeks * 7); exports.addWeeks = addWeeks; const addMonths = (date, months) => new Date(parseDate(date).setMonth(parseDate(date).getMonth() + months)); exports.addMonths = addMonths; const addYears = (date, years) => new Date(parseDate(date).setFullYear(parseDate(date).getFullYear() + years)); exports.addYears = addYears; /** Subtraction Operations */ const subtractDays = (date, days) => (0, exports.addDays)(date, -days); exports.subtractDays = subtractDays; const subtractWeeks = (date, weeks) => (0, exports.addWeeks)(date, -weeks); exports.subtractWeeks = subtractWeeks; const subtractMonths = (date, months) => (0, exports.addMonths)(date, -months); exports.subtractMonths = subtractMonths; const subtractYears = (date, years) => (0, exports.addYears)(date, -years); exports.subtractYears = subtractYears; /** Leap Year Check */ const isLeapYear = (date) => { const year = parseDate(date).getFullYear(); return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); }; exports.isLeapYear = isLeapYear; /** Month Details */ const getDaysInMonth = (date) => new Date(parseDate(date).getFullYear(), parseDate(date).getMonth() + 1, 0).getDate(); exports.getDaysInMonth = getDaysInMonth; const getFirstDayOfMonth = (date) => new Date(parseDate(date).getFullYear(), parseDate(date).getMonth(), 1); exports.getFirstDayOfMonth = getFirstDayOfMonth; const getLastDayOfMonth = (date) => new Date(parseDate(date).getFullYear(), parseDate(date).getMonth() + 1, 0); exports.getLastDayOfMonth = getLastDayOfMonth; /** Difference Between Dates */ const getDaysBetweenDates = (date1, date2) => Math.ceil(Math.abs(parseDate(date2).getTime() - parseDate(date1).getTime()) / 86400000); exports.getDaysBetweenDates = getDaysBetweenDates; const getWeeksBetweenDates = (date1, date2) => Math.ceil((0, exports.getDaysBetweenDates)(date1, date2) / 7); exports.getWeeksBetweenDates = getWeeksBetweenDates; const getMonthsBetweenDates = (date1, date2) => { const d1 = parseDate(date1); const d2 = parseDate(date2); return ((d2.getFullYear() - d1.getFullYear()) * 12 + (d2.getMonth() - d1.getMonth())); }; exports.getMonthsBetweenDates = getMonthsBetweenDates; const getYearsBetweenDates = (date1, date2) => parseDate(date2).getFullYear() - parseDate(date1).getFullYear(); exports.getYearsBetweenDates = getYearsBetweenDates; /** Timezone Adjustments */ const getCurrentDateInTimezone = (timezone, formatStr = "yyyy-MM-dd HH:mm:ss") => { var _a, _b, _c, _d, _e, _f; try { const now = new Date(); const formatter = new Intl.DateTimeFormat("en-US", { timeZone: timezone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false, }); const parts = formatter.formatToParts(now); const year = (_a = parts.find((p) => p.type === "year")) === null || _a === void 0 ? void 0 : _a.value; const month = (_b = parts.find((p) => p.type === "month")) === null || _b === void 0 ? void 0 : _b.value; const day = (_c = parts.find((p) => p.type === "day")) === null || _c === void 0 ? void 0 : _c.value; const hour = (_d = parts.find((p) => p.type === "hour")) === null || _d === void 0 ? void 0 : _d.value; const minute = (_e = parts.find((p) => p.type === "minute")) === null || _e === void 0 ? void 0 : _e.value; const second = (_f = parts.find((p) => p.type === "second")) === null || _f === void 0 ? void 0 : _f.value; if (!year || !month || !day || !hour || !minute || !second) { throw new Error("Invalid date parts"); } const formattedDateStr = `${year}-${month}-${day} ${hour}:${minute}:${second}`; return formatDate(formattedDateStr, formatStr); } catch (error) { console.error("Error in getCurrentDateInTimezone:", error); return "Invalid Timezone"; } }; exports.getCurrentDateInTimezone = getCurrentDateInTimezone; const getTimezoneOffset = (date) => { try { return parseDate(date).getTimezoneOffset(); } catch (error) { console.error("Error in getTimezoneOffset:", error); return NaN; } }; exports.getTimezoneOffset = getTimezoneOffset; const getTimezoneName = () => Intl.DateTimeFormat().resolvedOptions().timeZone; exports.getTimezoneName = getTimezoneName; const getTimezoneAbbreviation = (date) => { try { return new Intl.DateTimeFormat("en-US", { timeZoneName: "short" }).format(parseDate(date)); } catch (error) { console.error("Error in getTimezoneAbbreviation:", error); return "Invalid Timezone"; } }; exports.getTimezoneAbbreviation = getTimezoneAbbreviation; /** Daylight Saving Time Adjustments */ const isDaylightSavingTime = (date) => { try { const d = parseDate(date); return (d.getTimezoneOffset() !== new Date(d.getFullYear(), 0, 1).getTimezoneOffset()); } catch (error) { console.error("Error in isDaylightSavingTime:", error); return false; } }; exports.isDaylightSavingTime = isDaylightSavingTime; const getDSTStart = (date) => new Date(parseDate(date).getFullYear(), 2, 14, 2, 0, 0); // Second Sunday in March exports.getDSTStart = getDSTStart; const getDSTEnd = (date) => new Date(parseDate(date).getFullYear(), 10, 7, 2, 0, 0); // First Sunday in November exports.getDSTEnd = getDSTEnd; const getDSTOffset = (date) => { try { return (0, exports.isDaylightSavingTime)(date) ? -1 : 0; } catch (error) { console.error("Error in getDSTOffset:", error); return 0; } }; exports.getDSTOffset = getDSTOffset; /** Daylight Saving Time Adjustments in Timezone */ const getDSTStartInTimezone = (timezone, formatStr = "yyyy-MM-dd HH:mm:ss") => { var _a, _b, _c, _d, _e, _f; try { const now = new Date(); const year = now.getFullYear(); // DST starts on the Second Sunday of March at 2:00 AM in most regions const dstStart = new Date(Date.UTC(year, 2, 8, 2, 0, 0)); // March 8th (UTC time) while (dstStart.getUTCDay() !== 0) { dstStart.setUTCDate(dstStart.getUTCDate() + 1); // Move to next Sunday } // Convert to the given timezone const formatter = new Intl.DateTimeFormat("en-US", { timeZone: timezone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false, }); const parts = formatter.formatToParts(dstStart); const yearPart = (_a = parts.find((p) => p.type === "year")) === null || _a === void 0 ? void 0 : _a.value; const monthPart = (_b = parts.find((p) => p.type === "month")) === null || _b === void 0 ? void 0 : _b.value; const dayPart = (_c = parts.find((p) => p.type === "day")) === null || _c === void 0 ? void 0 : _c.value; const hourPart = (_d = parts.find((p) => p.type === "hour")) === null || _d === void 0 ? void 0 : _d.value; const minutePart = (_e = parts.find((p) => p.type === "minute")) === null || _e === void 0 ? void 0 : _e.value; const secondPart = (_f = parts.find((p) => p.type === "second")) === null || _f === void 0 ? void 0 : _f.value; if (!yearPart || !monthPart || !dayPart || !hourPart || !minutePart || !secondPart) { throw new Error("Invalid date parts"); } const formattedDateStr = `${yearPart}-${monthPart}-${dayPart} ${hourPart}:${minutePart}:${secondPart}`; return formatDate(formattedDateStr, formatStr); } catch (error) { console.error("Error in getDSTStartInTimezone:", error); return "Invalid Timezone"; } }; exports.getDSTStartInTimezone = getDSTStartInTimezone; exports.getDSTEndInTimezone = exports.getDSTStartInTimezone; // Since it's the same logic, reusing function. const getDSTOffsetInTimezone = (timezone, date) => { const d = parseDate(date); return (d.getTimezoneOffset() - new Date(d.getFullYear(), 0, 1).getTimezoneOffset()); }; exports.getDSTOffsetInTimezone = getDSTOffsetInTimezone;