Calculation Methods
valueOf()
Signature
valueOf(): numberReturn Type
number - Returns the timestamp (milliseconds since Unix epoch) of the Chronos instance
Behavior & Notes
- Enables arithmetic and comparison operations when used with primitive conversion
- Automatically called when
Chronosinstance is used in numeric context - Equivalent to
getTimeStamp()method - Returns same value as JavaScript Date's
valueOf()
Examples
// Numeric comparison
const date1 = new Chronos('2025-01-01');
const date2 = new Chronos('2025-01-02');
date2 > date1; // true (automatically calls valueOf())
// Arithmetic operations
const diff = +new Chronos('2025-01-02') - +new Chronos('2025-01-01');
// diff = 86400000 (1 day in milliseconds)
// Explicit conversion
const timestamp = new Chronos().valueOf();
// timestamp = current time in millisecondsUse Cases
- Sorting arrays of
Chronosinstances - Calculating time differences
- Interoperability with libraries expecting numeric timestamps
add()
Signature
add(amount: number, unit: TimeUnit): ChronosParameters
amount: Number of units to addunit: Time unit to add ('year', 'month', 'day', etc.)
Return Type
Chronos - New instance with added time
Notes
- Returns new immutable instance
- Handles month/year overflow automatically
Example
new Chronos('2025-01-31').add(1, 'month'); // 2025-02-28Alternatives
- You can also use one/all of these methods as per your need, they're self-explanatory:
addDays()addHours()addMinutes()addMonths()addSeconds()addWeeks()addYears()
subtract()
Signature
subtract(amount: number, unit: TimeUnit): ChronosParameters
amount: Number of units to subtractunit: Time unit to subtract
Return Type
Chronos - New instance with subtracted time
Example
new Chronos('2025-03-31').subtract(1, 'month'); // 2025-02-28diff()
Returns the difference between current and another date in the given unit.
Signature
diff(other: ChronosInput, unit: TimeUnit): numberParameters
other: Date to compare withunit: Unit for difference
Return Type
number - Difference in specified units
Notes
- Returns signed difference (negative if other is after this date)
Example
const date1 = new Chronos('2025-01-01');
const date2 = new Chronos('2025-01-15');
date2.diff(date1, 'days'); // 14round()
Note
This method is provided by roundPlugin. You must register it using Chronos.use(roundPlugin) before calling .round(). Once registered, all Chronos instances will have access to the .round() method.
Signature
round(unit: TimeUnit, nearest?: number): ChronosParameters
unit: The time unit to round to. Valid units:'year','month','week','day','hour','minute','second','millisecond'nearest: (optional): The nearest multiple to round to. Defaults to1.
Return Type
Chronos - Returns a new Chronos instance rounded to the nearest point based on the specified unit and granularity. If an invalid unit is passed, the original instance is returned unchanged.
Behavior & Notes
- Rounding is based on the proximity to the start or end of the specified time unit
- Rounding uses sub-unit fractions (e.g., seconds within minutes, minutes within hours) to determine proximity precisely.
nearestdefines the multiple to round to (e.g., 15-minute intervals), internally uses roundToNearest.- Rounding applies fractional logic based on how far into the unit the date is.
- If an invalid unit is passed, returns the original instance unchanged.
- Returns a new immutable
Chronosinstance (does not modify the original).
Unit-specific Behavior
-
Milliseconds/Seconds/Minutes/Hours:
- Rounds based on fractional components
- Example:
14:35:30rounded to nearest 15 minutes becomes14:30:00
-
Days:
- Rounds to nearest day based on time of day
- Example:
2025-05-23T18:00:00rounds to2025-05-24T00:00:00
-
Weeks:
- Uses ISO 8601 convention: weeks start on Monday.
- Rounds to nearest Monday based on proximity
- Rounding is determined by comparing the current date to:
- The start of the current week (Monday at 00:00),
- The start of the next week (the following Monday at 00:00).
- If the current date is closer to the next Monday, it rounds forward. Otherwise, it rounds back to the previous (or same) Monday.
- Rounded weeks are treated as 0-indexed relative to the year.
- Example: Once the current date passes midweek (e.g., late Wednesday or beyond), it becomes closer to the next Monday, so rounding moves forward to that Monday’s start.
-
Months:
- Rounds based on progress through the month (midpoint is day 15)
- Example:
2025-01-20rounds to2025-02-01
-
Years:
- Considers day-of-year progress relative to leap years
- Example:
2025-07-01(midyear) rounds to2026-01-01
Examples
import { roundPlugin } from 'chronos-date/plugins/roundPlugin';
Chronos.use(roundPlugin);
// Round to nearest hour
new Chronos('2025-01-15T14:35:30').round('hour');
// Returns: 2025-01-15T15:00:00
// Round to nearest 15 minutes
new Chronos('2025-01-15T14:35:30').round('minute', 15);
// Returns: 2025-01-15T14:30:00
// Round to nearest month (past midpoint)
new Chronos('2025-01-20').round('month');
// Returns: 2025-02-01T00:00:00
// Round to nearest week (closer to next Monday)
new Chronos('2025-01-16T18:00:00').round('week');
// Returns: 2025-01-20T00:00:00 (next Monday)duration()
Returns the full time duration breakdown between current input (start) and another time (to) as TimeDuration object.
Note
This method is provided by durationPlugin. You must register it using Chronos.use(durationPlugin) before calling .duration(). Once registered, all Chronos instances will have access to the .duration() method.
Signature
duration(toTime?: ChronosInput, absolute?: boolean): TimeDurationParameters
toTime: End date (default:now)absolute: Return absolute value, always positive iftrue(default:true)
Return Type
TimeDuration - Object with breakdown
interface TimeDuration {
/** Total number of years. */
years: number;
/** Number of months remaining after full years are counted. */
months: number;
/** Number of days remaining after full months are counted. */
days: number;
/** Number of hours remaining after full days are counted. */
hours: number;
/** Number of minutes remaining after full hours are counted. */
minutes: number;
/** Number of seconds remaining after full minutes are counted. */
seconds: number;
/** Number of milliseconds remaining after full seconds are counted. */
milliseconds: number;
}Example
import { durationPlugin } from 'chronos-date/plugins/durationPlugin';
Chronos.use(durationPlugin);
new Chronos('2020-01-01').duration('2025-01-01');
// {years: 3, months: 0, days: 0, ...}See Also
- For string output, please refer to durationString method.
durationString()
Returns a human-readable formatted duration string between the current instance (start) and another time (to).
Note
This method is provided by durationPlugin. You must register it using Chronos.use(durationPlugin) before calling .durationString(). Once registered, all Chronos instances will have access to the .durationString() method.
Signature
durationString(options?: DurationOptions): stringParameters
DurationOptions configuration object:
| Parameter | Type | Default | Description |
|---|---|---|---|
toTime | ChronosInput | now | The end time to calculate duration against |
absolute | boolean | true | Return absolute value, always positive if true |
maxUnits | NumberRange<1, 7> | 7 | Maximum number of time units to display |
separator | string | ", " | Separator between units in the output string |
style | "full" | "short" | "full" | Display format: "full" for full words, "short" for abbreviations |
showZero | boolean | false | Whether to include units with zero values |
Return Type
string - Human-readable formatted duration string
Description
Returns a human-readable string representation of the duration between the current Chronos instance (start time) and another specified time. The method provides flexible formatting options to control the output format, including the number of units displayed, formatting style, and zero-value handling.
Examples
import { durationPlugin } from 'chronos-date/plugins/durationPlugin';
Chronos.use(durationPlugin);
// Basic usage - with default options
new Chronos('2020-01-01').durationString({ toTime: '2025-01-01' });
// "5 years"
// Short style with default options
new Chronos('2020-01-01').durationString({
toTime: '2025-01-01',
style: 'short',
});
// "5y"
// Custom separator and showing only non-zero values
new Chronos('2023-01-01 10:30:00').durationString({
toTime: '2023-01-01 12:45:30',
separator: ' · ',
maxUnits: 3
});
// "2 hours · 15 minutes · 30 seconds"
// Short format for compact display
new Chronos('2023-01-01 10:30:00').durationString({
toTime: '2023-01-01 12:45:30',
style: 'short',
separator: ' ',
maxUnits: 2
});
// "2h 15m"
// Including zero values
new Chronos('2023-01-01').durationString({
toTime: '2023-01-01',
showZero: true,
maxUnits: 3
});
// "0 years, 0 months, 0 days"
// Empty duration fallback
new Chronos('2023-01-01').durationString({
toTime: '2023-01-01',
showZero: false
});
// "0 seconds"Notes
- When
showZeroisfalse(default), only units with non-zero values are included in the output. - The
maxUnitsparameter limits the number of time units displayed, starting from the largest unit (years). It respectsshowZerooption. - The method automatically handles pluralization in
"full"style (e.g.,"1 second"vs"2 seconds"). - If all filtered values are zero and
showZeroisfalse, returns"0 seconds"or"0s"depending on style. - Short style abbreviations:
years(y),months(mo),days(d),hours(h),minutes(m),seconds(s),milliseconds(ms).
See Also
- To implement custom formatting or logic, use the duration method. It provides a full duration object that offers greater control and flexibility for advanced scenarios.
getDatesInRange()
Generate an array of ISO date strings within a specified date range.
Note
This method is provided by dateRangePlugin. You must register it using Chronos.use(dateRangePlugin) before calling .getDatesInRange(). Once registered, all Chronos instances will have access to the .getDatesInRange() method.
Signatures
getDatesInRange(options?: RangeWithDates): ISOTimeString[]Overview
Generates dates between two points in time with:
- Fixed date ranges (
from/to) or relative ranges (span/unit) - Weekday filtering (
skipDays/onlyDays) - Format control (
local/utc) - Date boundary rounding
Parameters
options (Optional)
Configuration object accepting either fixed or relative range parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
from | ChronosInput | Current date | Start date (inclusive) |
to | ChronosInput | 4 weeks from now | End date (inclusive) |
span | number | 4 | Number of time units |
unit | 'year'|'month'|'week'|'day' | 'week' | Unit of time for relative ranges |
format | 'local'|'utc' | 'local' | Output format for ISO strings |
skipDays | WeekDay[] | Enumerate<7>[] | [] | Weekdays to exclude (e.g. ['Sunday', 'Saturday'] or [0, 6]) |
onlyDays | WeekDay[] | Enumerate<7>[] | [] | Include these (e.g. ['Monday'] or [1], overrides skipDays) |
roundDate | boolean | false | Round dates to start of day |
interface RangeWithDates {
/** Start date (inclusive). Default: current date */
from?: ChronosInput;
/** End date (inclusive). Default: 4 weeks from now */
to?: ChronosInput;
/** Output format. Default: 'local' */
format?: 'local' | 'utc';
/**
* An array of weekdays to exclude from the date range.
* - Accepts either weekday names (e.g., `'Saturday'`, `'Sunday'`) or numeric indices (0 for Sunday to 6 for Saturday).
* - Ignored if `onlyDays` is provided.
*/
skipDays?: Array<WeekDay> | Array<Enumerate<7>>;
/**
* An array of weekdays to explicitly include in the date range.
* - Accepts either weekday names (e.g., `'Monday'`, `'Wednesday'`) or numeric indices (0 for Sunday to 6 for Saturday).
* - When provided, this overrides `skipDays` and includes only the specified days.
*/
onlyDays?: Array<WeekDay> | Array<Enumerate<7>>;
/** Round dates to start of day. Default: false */
roundDate?: boolean;
}Return Value
ISOTimeString[] - Array of ISO date strings
Behavior
- Fixed ranges: Includes all dates between
fromandto(inclusive) - Relative ranges: Generates dates forward from current date
onlyDaystakes precedence overskipDayswhen both are provided- Defaults to
4-week rangewhen no options provided
Note
- When using
Chronosinstances forfromand/orto, ensure both are created in the same time zone to avoid mismatched boundaries. - Mixing zones may shift the interpreted start or end by several hours, which can cause the range to include or exclude incorrect weekdays.
Examples
import { dateRangePlugin } from 'chronos-date/plugins/dateRangePlugin';
Chronos.use(dateRangePlugin);
// Get all dates in January 2025
new Chronos().getDatesInRange({
from: '2025-01-01',
to: '2025-01-31',
skipDays: ['Saturday', 'Sunday'] // or [6, 0]
});
// Include only Fridays in a full month range
const now = new Chronos();
now.getDatesInRange({
from: now.startOf('month'),
to: now.endOf('month'),
onlyDays: ['Friday'],
roundDate: true
});
// Include only Mondays and Wednesdays in the range
new Chronos().getDatesInRange({
from: '2025-07-01',
to: '2025-07-15',
onlyDays: ['Monday', 'Wednesday']
});Notes
Important
- Weekday names must exactly match:
'Monday','Tuesday', etc. (case-sensitive) - When using
onlyDays, all other days are excluded regardless ofskipDays
Similar Static Method