Skip to main content

Chronos - Play with Time and Date, Be a Time Master like Chronos

Chronos​

About Chronos

In ancient Greek mythology, Chronos is the primordial embodiment of time — not merely tracking moments, but defining their very existence. Like its mythological namesake, the Chronos class offers precise, immutable, and expressive control over time within your application.

Designed to go beyond Date, it empowers you to manipulate, format, compare, and traverse time with clarity, reliability, and confidence — all while staying immutable and framework-agnostic.

Whether you're building a calendar, a countdown, or scheduling logic, Chronos gives you the power to shape time as you see fit.

API Reference for Chronos​

This documentation provides a detailed guide to the Chronos class, a comprehensive date and time manipulation class. The methods are grouped into logical categories for easier navigation.

info

For chronos function, a Chronos wrapper, refer to chronos

Import​

import { Chronos } from 'nhb-toolbox';
// or
import { Chronos } from 'nhb-toolbox/chronos';

Plugin System​

Chronos supports a modular plugin system that allows you to extend its capabilities without bloating the core. Plugin methods are not available by default, you must explicitly install them using the .use() or .register() static method.

How it works​

import { Chronos } from 'nhb-toolbox';
import { seasonPlugin } from 'nhb-toolbox/plugins/seasonPlugin';

// Register the plugin before using its methods
Chronos.use(seasonPlugin);
// or
Chronos.register(seasonPlugin);

const now = new Chronos();
console.log(now.season()); // ✅ Safe to use after plugin registration
info

Each plugin enhances the Chronos prototype and becomes available globally after registration.

Constructor Signatures​

 constructor();
constructor(value: number);
constructor(value: string);
constructor(value: Date);
constructor(value: Chronos);
constructor(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number);
constructor(value?: ChronosInput);

ChronosInput​

type ChronosInput = number | string | Date | Chronos;

Public & Protected Properties​

These properties provide non-destructive, read-only (only the core ones) access to the copies of internal states of a Chronos instance for debugging, inspection, or meta-awareness.

info

However, in JavaScript, these properties can technically be mutated (Compile-time Error occurs in TypScript if these properties are tried to be mutated), but such mutations (changes) do not affect the Chronos instance itself. The class internally manages equivalent strict readonly/private state. These public properties exist purely for developer convenience and sugar.

native: Date​

Returns the underlying native JavaScript Date object used internally by the Chronos instance. This is useful for interoperability with APIs or libraries that expect a native Date.

Info

Equivalent to toDate() instance method.

const ch = new Chronos('2025-01-01');
console.log(ch.native.toISOString()); // → 2025-01-01T00:00:00.000Z

origin: ChronosMethods | 'root'​

Indicates how the current Chronos instance was created. This can be helpful for debugging flow logic or tracing method chains in complex date-time pipelines.

Possible values:

  • 'root': if the instance was directly constructed
  • A method name string such as 'addDays', 'startOf', etc., if the instance was produced as the result of a method call (which can create a new instance of Chronos). If no such method was called it shows the last previous method name as origin, if there is none, it shows root.
const root = new Chronos();
const viaMethod = root.addDays(3);

console.log(root.origin); // → 'root'
console.log(viaMethod.origin); // → 'addDays'

utcOffset: UTCOffset​

Returns the current UTC offset in UTC±HH:mm format (e.g., "UTC+06:00", "UTC-05:30").

Info
  • Also accessible via getTimeZoneOffset() instance method without UTC prefix (returns in ±HH:mm format).
  • This value is automatically updated when using timezone or UTC manipulation methods.
const ch = new Chronos('2025-01-01');
console.log(ch.utcOffset); // → "UTC+06:00"

const ny = ch.timeZone('America/New_York');
console.log(ny.utcOffset); // → "UTC-05:00" (or UTC-04:00 during DST)
Caution

This property is mutable, but modifying it has no effect on the Chronos instance. Any logic that relies on the mutated value may behave incorrectly, as Chronos internally derives its actual state from private fields.

timeZoneName: LooseLiteral<TimeZoneName>​

Represents the current timezone name (e.g., "Bangladesh Standard Time"), or falls back to the corresponding timezone identifier (e.g., "Asia/Dhaka") if no name can be resolved.

Remarks
  • Invoking the timeZone() method sets the timezone name that corresponds to the specified UTC offset, or the UTC offset itself if no name exists. For more details on this behavior, see getTimeZoneName().
  • To retrieve the local system's native timezone name (or its identifier if the name is unavailable), use the $getNativeTimeZoneName() instance method.
const ch = new Chronos('2025-01-01');
console.log(ch.timeZoneName); // → "Bangladesh Standard Time"

const custom = ch.timeZone('UTC+02:45');
console.log(custom.timeZoneName); // → "UTC+02:45" (no named timezone)
Caution

This property is mutable, but modifying it has no effect on the Chronos instance. Any logic that relies on the mutated value may behave incorrectly, as Chronos internally derives its actual state from private fields.

timeZoneId: TimeZoneId​

Represents the current timezone context, which can be a single identifier, an array of equivalent identifiers, or a UTC offset.

Possible return types:

  • $TimeZoneIdentifier — e.g., "Asia/Dhaka". Returned when the timeZone() method has not been invoked (default behavior).
  • Array of $TimeZoneIdentifier — e.g., ['Asia/Kathmandu', 'Asia/Katmandu'], used when multiple timezones share the same UTC offset such as "UTC+05:45".
  • UTCOffset — e.g., "UTC+06:45" or "UTC+02:15", returned when no named timezone corresponds to a given offset.
Remarks
  • By default, when timeZone() is not applied, a single $TimeZoneIdentifier string is provided.
  • When applied, it may instead return a single identifier string, an array of equivalent identifiers, or a UTC offset string.
  • To retrieve the local system's native timezone identifier, use the $getNativeTimeZoneId() instance method.
const ch = new Chronos('2025-01-01');
console.log(ch.timeZoneId); // → "Asia/Dhaka" (system timezone)

const multi = ch.timeZone('UTC+05:30');
console.log(multi.timeZoneId);
// → [ 'Asia/Calcutta', 'Asia/Colombo' ] (multiple equivalent zones)

const offsetOnly = ch.timeZone('UTC+02:15');
console.log(offsetOnly.timeZoneId); // → "UTC+02:15" (no named timezone)
Caution

This property is mutable, but modifying it has no effect on the Chronos instance. Any logic that relies on the mutated value may behave incorrectly, as Chronos internally derives its actual state from private fields.

$tzTracker?: $TimeZoneIdentifier | TimeZone | UTCOffset​

danger

[Protected] Internal flag used to track instances created via the timeZone() method. This value participates in the internal resolution of time-zone name, identifier, and offset. Although it is protected, it can still be mutated in JavaScript/TypeScript; and doing so may de-synchronize these time-zone properties and lead to inconsistent results. Avoid modifying this field unless you fully understand the implications.

Available Methods​

Getter Methods
MethodShort Description
yearGets the full year of the date.
monthGets the month (0-11) of the date.
dateGets the day of the month (1-31).
weekDayGets the day of the week (0-6, where 0 is Sunday).
hour,Gets the hour (0-23) of the date.
minuteGets the minute (0-59) of the date.
secondGets the second (0-59) of the date.
millisecondGets the millisecond (0-999) of the date.
isoWeekDayGets ISO weekday: 1 = Monday, 7 = Sunday.
isoMonthGets ISO month (1–12 instead of 0–11).
unixReturns the Unix timestamp (seconds since the Unix epoch).
timestampGets the time value in milliseconds since midnight, 1970-01-01 UTC.
lastDateOfMonthGets the last date (number) of the current month (28, 29, 30 or 31).
Format Methods
MethodShort Description
format()Formats the current date into a custom string format.
formatStrict()Formats the date into a predefined strict string format.
formatUTC()Formats the date into a custom string format (UTC time).
calendar()Returns a human-readable relative calendar time like "Today at 3:00 PM"
fromNow()Returns full time difference as string down to a given level.
fromNowShort()Returns a short human-readable string like "2h ago", "in 5m".
getGreeting()Returns a greeting message based on Chronos instance or provided time.
greet()Alias for getGreeting()
Calculation Methods
MethodShort Description
valueOf()Enables arithmetic and comparison operations (e.g., +new Chronos()).
add()Returns a new Chronos instance with the specified unit added.
addDays()Adds days and returns a new immutable instance.
addHours()Adds hours and returns a new immutable instance.
addMinutes()Adds minutes and returns a new immutable instance.
addMonths()Adds months and returns a new immutable instance.
addSeconds()Adds seconds and returns a new immutable instance.
addWeeks()Adds weeks and returns a new immutable instance.
addYears()Adds years and returns a new immutable instance.
subtract()Returns a new Chronos instance with the specified unit subtracted.
diff()Returns the difference between current and another date.
duration()Returns full time duration between current and another time object.
durationString()Returns a human-readable formatted duration string between 2 dates.
round()Rounds the current date-time to the nearest unit and interval.
getDatesInRange()Generates a list of ISO date strings within a specified range.
Name Getter Methods
MethodShort Description
day()Returns the name of the current day or optional day index.
monthName()Returns the name of the current month or optional month index.
$getNativeTimeZoneName()Retrieves the local system's current timezone name.
$getNativeTimeZoneId()Retrieves the IANA time zone identifier for the local system.
getTimeZoneName()Returns the current time zone name in descriptive string.
getTimeZoneNameShort()Returns the current time zone abbreviation (e.g. "BST").
getTimeZoneNameAbbr()Get time zone abbreviation (Alias of getTimeZoneNameShort()).
season()Returns the current season name based on options.
getSeasonName()Alias for season()
getZodiacSign()Returns the zodiac sign based on current date or birthDate.
zodiac()Alias for getZodiacSign()
getPartOfDay()Returns the part of day based on the current hour.
Checker Methods
MethodShort Description
isAfter()Checks if this date is after another date in a specific unit.
isBefore()Checks if this date is before another date in a specific unit.
isBetween()Checks if the current date is between the given start and end dates.
isSame()Checks if another date is the same as this one in a specific unit.
isSameOrAfter()Checks if this date is same or after another in a specific unit.
isSameOrBefore()Checks if this date is same or before another in a specific unit.
isEqual()Checks if another date is exactly equal to this one.
isEqualOrAfter()Checks if another date is exactly equal to or after this one.
isEqualOrBefore()Checks if another date is exactly equal to or before this one.
isBusinessHour()Checks if the current date and time fall within business hours.
isWeekend()Checks if the current date falls on a weekend.
isWorkday()Checks if the current date is a workday.
isFirstDayOfMonth()Checks if current day is the first day of the current month.
isLastDayOfMonth()Checks if current day is the last day of the current month.
isToday()Checks if the current date is today.
isTomorrow()Checks if the current date is tomorrow.
isYesterday()Checks if the current date is yesterday.
isLeapYear()Checks if the current year is a leap year.
isPalindromeDate()Checks if the current date (date part only) is a palindrome.
isDST()Checks if the date is within daylight saving time (DST).
Conversion Methods
MethodShort Description
clone()Clones and returns exactly same Chronos instance.
toUTC()Returns new Chronos instance in UTC time.
toLocal()Returns new Chronos instance in local time.
timeZone()Creates a new instance of Chronos for the specified time zone information.
toDate()Gets the native Date instance.
toArray()Converts to array with all date unit part
toObject()Converts to object with all date unit parts
Comparison Methods
MethodShort Description
compare()Returns the difference of 2 dates in specified unit.
getRelativeDay()Returns the number of days between 2 dates.
getRelativeHour()Returns the number of hours between 2 dates.
getRelativeMinute()Returns the number of minutes between 2 dates.
getRelativeSecond()Returns the number of seconds between 2 dates.
getRelativeMilliSecond()Returns the number of milliseconds between 2 dates.
getRelativeWeek()Returns the number of weeks between 2 dates.
getRelativeMonth()Returns the number of months between 2 dates.
getRelativeYear()Returns the number of years between 2 dates.
Get & Set Methods
MethodShort Description
get()Gets the value of a specific time unit from the date.
set()Returns a new instance with the specified unit set to the given value.
startOf()Returns a new Chronos instance at the start of a given unit.
endOf()Returns a new Chronos instance at the end of a given unit.
getWeek()Calculates the ISO 8601 week number of the year.
setWeek()Sets the date to the specified ISO week number within the current year.
getWeekOfYear()Calculates the week number of the year based on custom week start.
getWeekYear()Returns the ISO week-numbering year for the current date.
getDayOfYear()Returns day of year (1 - 366).
getTimeStamp()Returns the time value in milliseconds since midnight, 1970-01-01 UTC.
daysInMonth()Returns number of days in current month.
firstDayOfMonth()Returns a new instance set to the first day of the current month.
lastDayOfMonth()Returns a new instance set to the last day of the current month.
String Methods
MethodShort Description
toString()Returns a string representation of a date.
toISOString()Returns a date as a string value in ISO format (UTC).
toLocalISOString()Returns ISO time string in appropriate time zone with offset.
toLocaleString()Wrapper over native JS toLocaleString with improved type system.
toJSON()Enables JSON.stringify to show readable output.
inspect()Returns a debug-friendly string for console.log or util.inspect.
Extra Time Information
MethodShort Description
getUTCOffset()Returns the system's UTC offset formatted as ±HH:mm
getTimeZoneOffset()Returns the timezone offset in ±HH:mm format
getUTCOffsetMinutes()Gets difference in mins between UTC and local system.
getTimeZoneOffsetMinutes()Returns the current instance's UTC offset in minutes.
toQuarter()Returns the calendar quarter (1 to 4) of the instance.
toFiscalQuarter()Returns the fiscal quarter based on custom start month.
toAcademicYear()Returns the academic year in format YYYY-YYYY.
Static Methods
MethodShort Description
now()Returns the number of milliseconds elapsed since midnight, 1970-01-01 UTC.
use()Injects a plugin into the Chronos system.
register()Alias for use()
utc()Creates a UTC-based Chronos instance.
with()Creates a new Chronos instance with the provided time component(s).
parse()Parses a date string with a given format (limited support only).
max()Returns latest Chronos.
min()Returns earliest Chronos.
today()Returns the current date and time in a specified format in local time.
tomorrow()Returns a new Chronos instance representing tomorrow's date.
yesterday()Returns a new Chronos instance representing yesterday's date.
formatTimePart()Formats a time-only string into a formatted time string.
getDatesForDay()Returns ISO date strings for each occurrence of a weekday.
isLeapYear()Checks if the year in the date or year (from 0 - 9999) is a leap year.
isValidChronos()Checks if the given value is an instance of Chronos.
isValidDate()Checks if the given value is a valid Date object.
isDateString()Checks if the given value is a valid date string.
Symbol Methods
MethodShort Description
Symbol.iteratorReturns the default iterator for an object.
Symbol.toPrimitiveConverts an object to a corresponding primitive value.
Symbol.replaceRegExp method, replaces matched parts of a string.
Symbol.searchRegExp method, returns index within a matched string.
Symbol.splitRegExp method, splits a string at the matched indices.
Symbol.matchRegExp method, matches the RegExp against a string.
Symbol.toStringTagCalled by the built-in Object.prototype.toString.
Symbol.isConcatSpreadableEnables to be spread with the spread operator ...

Alias​

The Chronos class is also available as Chronus alias.