timezone-date-utils
v1.2.13
Published
Comprehensive date and time utilities using moment-timezone with IST as default timezone. Features strict TypeScript types, type guards, validators, and runtime assertions. Works seamlessly in both Node.js backend and browser frontend environments.
Maintainers
Readme
timezone-date-utils
Timezone-aware date and time utilities for hospitality and booking systems, built on
moment-timezone with Indian Standard Time
(Asia/Kolkata) as the default timezone. Ships 170+ strictly-typed functions,
constants, type guards, and runtime validators that behave identically in Node.js
services and browser applications.
Developed and maintained by Vishal Meena and used in production hotel property-management systems.
Contents
- Why this library
- Installation
- Quick start
- Compatibility
- API overview
- Timezone handling
- Constants
- TypeScript
- Hotel operations
- Versioning
- Contributing
- License
Why this library
General-purpose date libraries leave timezone discipline, format governance, and domain rules to the application. This library encodes them once:
| Concern | What you get |
| --- | --- |
| Timezone correctness | Every operation is timezone-aware; IST by default, any IANA zone on demand. No accidental host-machine-local arithmetic. |
| Format governance | DateFormat is a closed union of vetted format strings. Format-string typos are compile-time errors, not silent bad output. |
| Runtime safety | Type guards, validators, and assertions for untrusted input — branded types (ISODateString, UnixTimestamp, PositiveInteger) prove validation happened. |
| Domain logic | Night calculation, check-in/check-out cutoffs, night-audit dates, business-day math, range-overlap detection. |
| Universality | One package, identical behavior in Node.js backends (NestJS, Express) and browser frontends (React, Next.js, Vue, Angular). |
Installation
npm install timezone-date-utils moment-timezone
# or
pnpm add timezone-date-utils moment-timezone
# or
yarn add timezone-date-utils moment-timezonemoment-timezone (^0.5.48) is a peer dependency and must be installed alongside
the package.
Quick start
import {
now,
createDate,
formatDisplay,
calculateNights,
isWeekend,
} from 'timezone-date-utils';
const currentTime = now(); // current moment in IST
const checkIn = createDate('2026-08-15');
const checkOut = createDate('2026-08-18');
formatDisplay(checkIn); // "15 Aug 2026"
calculateNights(checkIn, checkOut); // 3
isWeekend(checkIn); // true (Saturday)Namespace import works equally well:
import * as DateUtil from 'timezone-date-utils';
DateUtil.now('America/New_York'); // current moment in EST/EDTValidating untrusted input before it enters your domain model:
import { toISODateString, toPositiveInteger, calculateNights } from 'timezone-date-utils';
const checkIn = toISODateString(req.body.checkIn); // ISODateString | null
const checkOut = toISODateString(req.body.checkOut);
if (!checkIn || !checkOut) throw new BadRequestException('Invalid dates');
const nights = toPositiveInteger(calculateNights(checkIn, checkOut));
if (!nights) throw new BadRequestException('Stay must be at least one night');Compatibility
| Environment | Support |
| --- | --- |
| Node.js | >= 14 |
| Module systems | CommonJS (require) and ES modules (import) |
| Browsers | All evergreen browsers, via any bundler (webpack, Vite, esbuild, Rollup) |
| TypeScript | Full declarations shipped (dist/types); strict mode supported |
Module resolution
As of v1.2.11, both the import and require conditions of the package
resolve to the CommonJS build. Node.js imports CommonJS with full named-export
interop, so both of these are supported and return the same module instance
(no dual-package hazard):
import { now } from 'timezone-date-utils'; // ESM consumers
const { now } = require('timezone-date-utils'); // CJS consumersVersions ≤ 1.2.10 advertised an ES-module build that could not be loaded by Node.js (missing module-type marker and extensionless relative imports). Upgrade to
>= 1.2.11; no code changes are required.
API overview
The package exports ~170 functions grouped by concern. The most commonly used are listed below; see the Quick Reference for the complete surface.
Creation and parsing
| Function | Description |
| --- | --- |
| now(timezone?) | Current moment in IST or the given IANA zone |
| createDate(input, timezone?) | Create from string, Date, timestamp, or moment |
| parseDate(value, format) / parseDateStrict(value, format) | Parse with an explicit format |
| parseMultipleFormats(value, formats) | Try several formats in order |
| fromTimestamp(ms) / fromUnix(seconds) | From epoch values |
| fromComponents(y, m, d, h?, min?, s?) | From numeric components |
Formatting
| Function | Output example |
| --- | --- |
| formatDisplay(date) | "15 Aug 2026" |
| formatDisplayWithTime(date) | "15 Aug 2026, 02:00 PM" |
| toISOString(date) | "2026-08-15T14:00:00.000+05:30" |
| toISODate(date) | "2026-08-15" |
| toDBFormat(date) | "2026-08-15 14:00:00" |
| formatIndianDate(date) / formatIndianDateSlash(date) | "15-08-2026" / "15/08/2026" |
| formatInvoiceDate(date) | "15-08-2026, 2:00 PM" |
| formatTimeOnly(date) / formatTime12Hour(date) | "14:00" / "02:00 PM" |
| separateDateTime(date) | { date: "15-08-2026", time: "14:00" } |
| toDateKey(date) / toMonthKey(date) / toWeekKey(date) | Grouping keys: "2026-08-15", "2026-08", "2026-W33" |
Arithmetic and comparison
| Function | Description |
| --- | --- |
| add(date, n, unit) / subtract(date, n, unit) | Unit-based arithmetic |
| addDuration(date, duration) / subtractDuration(date, duration) | Object-based arithmetic ({ days: 3, hours: 2 }) |
| startOf(date, unit) / endOf(date, unit) | Period boundaries |
| isBefore / isAfter / isSame / isSameOrBefore / isSameOrAfter / isBetween | Comparisons |
| diff(a, b, unit) / diffInDays / diffInHours / diffInMinutes | Signed differences |
| min(dates) / max(dates) / sortDatesAscending(dates) | Aggregation and ordering |
Queries and validation
| Function | Description |
| --- | --- |
| isValid / isToday / isYesterday / isTomorrow / isPast / isFuture | Point-in-time queries |
| isWeekend / isWeekday / isLeapYear / isSameDay | Calendar queries |
| isValidYYYYMMDD / isValidDDMMYYYY / isValidDDMMYYYYSlash | String-format validation |
| calculateAge(dob) / calculateAgeFromDDMMYYYY(dob) / getDetailedAge(dob) | Age computation |
Ranges
| Function | Description |
| --- | --- |
| createDateRange(start, end) / dateRange(start, end) | Range construction and enumeration |
| getDateArray(start, end) / dateRangeInChunks(start, end, size) | Materialized ranges, chunked for large spans |
| doRangesOverlap(aStart, aEnd, bStart, bEnd) / getOverlapDays(...) | Overlap detection — reservation-collision safe |
| getTodayRange() / getThisWeekRange() / getThisMonthRange() / getThisYearRange() / getLastNDaysRange(n) | Predefined reporting ranges |
Business days
| Function | Description |
| --- | --- |
| getNextBusinessDay() / getPreviousBusinessDay() | Weekday navigation |
| countBusinessDays(start, end) | Weekday count over a span |
Timezone handling
All functions default to IST (Asia/Kolkata) and accept an explicit IANA
timezone where relevant. Named constants are provided for common zones:
import { TIMEZONES, now, toTimezone } from 'timezone-date-utils';
TIMEZONES.IST // 'Asia/Kolkata' (default)
TIMEZONES.UTC // 'UTC'
TIMEZONES.DUBAI // 'Asia/Dubai'
TIMEZONES.SINGAPORE // 'Asia/Singapore'
TIMEZONES.EST // 'America/New_York'
now(TIMEZONES.UTC); // current moment in UTC
toTimezone(date, TIMEZONES.DUBAI); // convert an existing momentConstants
import {
DATE_FORMATS, // vetted format strings: ISO_DATE, DISPLAY_DATE, INDIAN_DATE, ...
DAY_OF_WEEK, // MONDAY = 1, ...
MONTH_OF_YEAR, // DECEMBER = 11 (0-indexed)
HOTEL_TIMINGS, // CHECK_IN_TIME '14:00', CHECK_OUT_TIME '11:00', LATE_CHECK_OUT_TIME '18:00'
BUSINESS_DAYS,
WEEKEND_DAYS,
MILLISECONDS_IN, // DAY = 86_400_000, ...
} from 'timezone-date-utils';TypeScript
The package is written in TypeScript with strict typing throughout.
Closed format union. DateFormat accepts only vetted format strings — an
arbitrary string is a compile-time error. New formats are added to the library
deliberately rather than scattered through application code.
Branded types. Values that have passed validation carry a brand, so a raw
string cannot be passed where a validated value is required:
import type {
ISODateString, ISODateTimeString, UnixTimestamp,
PositiveInteger, NonNegativeInteger,
DayOfWeek, // 0–6
MonthOfYear, // 0–11
HourOfDay, // 0–23
} from 'timezone-date-utils';Three validation tiers, for use at trust boundaries:
import {
isISODateString, // type guard → boolean, narrows in place
toISODateString, // validator → branded value | null
assertPositiveInteger, // assertion → throws with context on invalid input
TypeGuards, Validators, Assertions, // grouped namespaces
} from 'timezone-date-utils';See the Strict Types Guide for the complete reference.
Hotel operations
Domain functions used in production reservation, folio, and audit flows:
import {
calculateNights,
getCheckInTime,
getCheckOutTime,
isPastCheckIn,
isPastCheckOut,
getNightAuditDate,
} from 'timezone-date-utils';
calculateNights('2026-08-15', '2026-08-18'); // 3
getCheckInTime(checkIn); // the 14:00 check-in moment on that date
getCheckOutTime(checkOut); // the 11:00 check-out moment on that date
isPastCheckIn(); // has today's 14:00 cutoff passed?
getNightAuditDate(); // current audit business dateVersioning
This package follows Semantic Versioning. All notable changes are recorded in the CHANGELOG.
| Version | Notes |
| --- | --- |
| >= 1.2.11 | Recommended. Fixes the broken ES-module entry point; import and require both resolve to the CommonJS build. |
| 1.2.10 | Deprecated — metadata-only publish, no code changes over 1.2.9. |
| <= 1.2.9 | Loadable via require only; the advertised ESM entry fails under Node.js. |
Contributing
Issues and pull requests are welcome at vishalmeena2211/timezone-date-utils. See the Development Guide for build and release instructions.
License
MIT © Vishal Meena
