Calculation Methods
valueOf()β
Signatureβ
valueOf(): number
Return 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 milliseconds
Use Casesβ
- Sorting arrays of
Chronosinstances - Calculating time differences
- Interoperability with libraries expecting numeric timestamps
add()β
Signatureβ
add(amount: number, unit: TimeUnit): Chronos
Parametersβ
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-28
Alternativesβ
- 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): Chronos
Parametersβ
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-28
diff()β
Signatureβ
diff(other: ChronosInput, unit: TimeUnit): number
Parametersβ
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'); // 14
round()β
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): Chronos
Parametersβ
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 'nhb-toolbox/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()β
Signatureβ
duration(toTime?: ChronosInput, absolute?: boolean): TimeDuration
Parametersβ
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β
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()β
Signatureβ
durationString(options?: DurationOptions): string
Parametersβ
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β
// 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.
Signaturesβ
- Fixed Range
- Relative Range
- Implementation
getDatesInRange(options?: RangeWithDates): string[]
getDatesInRange(options?: RelativeDateRange): string[]
getDatesInRange(options?: DatesInRangeOptions): string[]
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 | Required | 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>[] | β | [] | Only include these weekdays (e.g. ['Monday'] or [1], overrides skipDays) |
roundDate | boolean | β | false | Round dates to start of day |
- Fixed Range Options
- Relative Range Options
- Implementation Options
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;
}
interface RelativeDateRange {
/** Number of time units. Default: 4 */
span?: number;
/** Unit of time. Default: 'week' */
unit?: 'year' | 'month' | 'week' | 'day';
/** 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;
}
/** - Unified type that supports either a fixed or relative date range configuration. */
export type DatesInRangeOptions = RangeWithDates | RelativeDateRange;
Return Valueβ
string[] - 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
Examplesβ
- Fixed Range
- Relative Range
- With Rounding
// 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']
});
// Get UTC dates for next 10 business days
new Chronos().getDatesInRange({
span: 10,
unit: 'day',
skipDays: ['Saturday', 'Sunday'], // or [6, 0]
format: 'utc'
});
// Include only Tuesdays (2) and Thursdays (4) over the next 10 days
new Chronos().getDatesInRange({
span: 10,
unit: 'day',
onlyDays: [2, 4],
});
// Get rounded dates for current month as local ISO string
const now = new Chronos();
now.getDatesInRange({
from: now.startOf('month'),
to: now.endOf('month'),
roundDate: true
});
Notesβ
- Weekday names must exactly match:
'Monday','Tuesday', etc. (case-sensitive) - When using
onlyDays, all other days are excluded regardless ofskipDays