native-dates

API / Classes

DateTime class

A specific moment in time, viewed in a time zone.

import { DateTime } from 'native-dates'core 14.9 kB min+br

Creating a DateTime

Create an instance from an existing value with datetime(), read the current time with now(), or combine a calendar date with a time using at(). Instances are immutable, so every method that changes a value returns a new one.

create.js
import { date, datetime, now } from 'native-dates';

const fromUtc = datetime('2026-11-16T17:30:00Z', 'America/Los_Angeles');
const standup = date('2026-11-16').at('9:30am', 'America/Los_Angeles');
const current = now();

Pass a time zone to view the instant in that zone, or omit it to use the default from configure():

const event = datetime('2026-11-16T17:30:00Z', 'America/New_York');
event.zone; // 'America/New_York'
event.hour; // 12

Offsets set the moment, not the zone

A trailing Z or numeric offset in an input string identifies when the moment happened, while the instance uses the zone you pass or your configured default. Pass 'UTC' as the zone when you want UTC fields and date math.

Properties

Properties read the date and time in the instance’s time zone.

Property Type Description
text string Locale-formatted date, time, and short zone name, such as 'Nov 16, 2026, 9:30 AM PST'.
year, month, day number Calendar year, month (1–12), and day of month (1–31).
hour, minute, second number 24-hour clock fields (0–23, 0–59, 0–59).
millisecond, microsecond, nanosecond number Sub-second clock fields (0–999).
zone string Canonical IANA zone ID or fixed offset, such as 'America/Los_Angeles' or 'UTC'.
offset string Active UTC offset at this instant, such as '-08:00'.
epochSeconds number Whole seconds since the Unix epoch, rounded down.
epochMilliseconds number Milliseconds since the Unix epoch.
epochNanoseconds bigint Exact nanoseconds since the Unix epoch.
date CalendarDate Calendar date in this time zone.
time Time Time of day in this time zone.
yearMonth YearMonth Calendar year and month in this time zone.
monthDay MonthDay Calendar month and day in this time zone.
dayOfWeek number ISO day of the week, from 1 for Monday through 7 for Sunday.
weekStart number First day of this moment’s weeks from 1 to 7, following configure() or its locale.
quarter number Calendar quarter (1–4).
weekOfYear, dayOfYear number ISO week number (1–53) and day of the year (1–366).
daysInMonth, daysInYear, hoursInDay number Length of the current month, year, and local calendar day.

Time zone and fields

View the same moment in another zone or replace individual calendar and clock fields.

in()

dt.in(zone): DateTime

Returns a new DateTime representing the same instant in another time zone. Local calendar and clock properties update to match the target zone, while the underlying timestamp stays the same.

zoneZonerequired

IANA time zone name such as 'Europe/Berlin', fixed UTC offset, or 'UTC'.

DateTime

A new DateTime at the same instant viewed in zone.

const standup = datetime('2026-11-16T09:30', 'America/Los_Angeles');
const berlin = standup.in('Europe/Berlin');

berlin.hour; // 18
berlin.equals(standup); // true

at()

dt.at(time): DateTime

Returns a new DateTime on the same day and in the same time zone, with the time of day replaced.

timeTimeInputrequired

Time string such as '9:30am', Time instance, fields object, or Date.

DateTime

A new DateTime on the same date at time.

const morning = datetime('2026-11-16T09:30', 'America/Los_Angeles');
const wrapUp = morning.at('5:00pm');

wrapUp.hour; // 17

set()

dt.set(fields): DateTime
dt.set(unit, value): DateTime

Returns a new DateTime with one or more calendar or clock fields replaced in the current time zone. Out-of-range dates such as February 30 throw a RangeError instead of rolling into the next month. Updating month or year without day clamps an overflowing day to the end of the target month.

fieldsDateTimeFields | Unitrequired

Object of calendar or clock fields, or a single unit name when passing value.

valuenumber

Whole-number value for the given unit.

DateTime

A new DateTime in the same time zone with updated fields.

const cutoff = datetime('2026-11-16T09:30', 'America/New_York');

cutoff.set('hour', 17);
cutoff.set({ month: 12, day: 1, hour: 0, minute: 0 });

Arithmetic and rounding

Adding days, weeks, months, or years keeps the same time of day across daylight saving changes. Adding hours, minutes, or seconds counts exact elapsed time.

plus()

dt.plus(amount, unit?): DateTime
dt.add(amount, unit?): DateTime

Moves forward by a duration and returns a new DateTime in the same time zone. Also aliased as add().

amountDurationInputrequired

Count paired with unit, Duration instance, duration string, fields object, or milliseconds.

unitUnit

Unit name when amount is a number, such as 'days' or 'hours'.

DateTime

A new DateTime in the same time zone.

// Spring-forward weekend in New York (March 8 has 23 hours)
const sat = datetime('2026-03-07T09:00', 'America/New_York');

sat.plus(1, 'day').hour; // 9
sat.plus(24, 'hours').hour; // 10
sat.plus('1h 30m').format('time', 'en-US'); // '10:30 AM'

minus()

dt.minus(amount, unit?): DateTime
dt.subtract(amount, unit?): DateTime

Moves backward by a duration in the same time zone. Accepts the same inputs as plus(), and is also aliased as subtract().

amountDurationInputrequired

A numeric count paired with unit, a Duration, a phrase, an ISO duration, or a fields object.

unitUnit

Unit name when amount is a number.

DateTime

A new DateTime in the same time zone.

const deadline = datetime('2026-11-16T17:00', 'America/New_York');

deadline.minus(48, 'hours');
deadline.minus({ weeks: 1, days: 2 });

startOf()

dt.startOf(unit, firstDay?): DateTime

Moves back to the start of a calendar or clock unit in this time zone. Week boundaries start on firstDay, the configured weekStart from configure(), or this moment’s active locale.

unitUnitrequired

Calendar or clock unit from 'year' down to 'millisecond'.

firstDayDayOfWeek

First day of the week when rounding to a week, such as 'sunday' or 7.

DateTime

A new DateTime at the start of unit.

const wed = datetime('2026-11-18T14:45:12', 'America/New_York').locale('en-US');

wed.startOf('day').format('time'); // '12:00 AM'
wed.startOf('week').day; // 15
wed.startOf('week', 'monday').day; // 16

endOf()

dt.endOf(unit, firstDay?): DateTime

Moves to the final millisecond of a calendar or clock unit in this time zone.

unitUnitrequired

Calendar or clock unit from 'year' down to 'nanosecond'.

firstDayDayOfWeek

First day of the week when unit is 'week'.

DateTime

A new DateTime at the last millisecond of unit.

const nov = datetime('2026-11-18T14:45', 'UTC');

nov.endOf('month').toString(); // '2026-11-30T23:59:59.999Z'

startOfNext()

dt.startOfNext(unit, firstDay?): DateTime

Moves forward to the start of the calendar or clock unit after the one containing this moment, in this time zone. The result is always a later moment, so from midnight the next day starts at the following midnight.

Pass a weekday name in place of a unit to get the start of the next day with that name. Calling next() finds the same day and keeps the time of day.

unitUnit | Exclude<DayOfWeek, number>required

Calendar or clock unit from 'year' down to 'nanosecond', or a weekday name such as 'wednesday'.

firstDayDayOfWeek

First day of the week when unit is 'week'.

DateTime

A new DateTime at the start of the next unit, or of the next given weekday.

const standup = datetime('2026-11-16T09:30', 'America/New_York');

standup.startOfNext('month').text; // 'Dec 1, 2026, 12:00 AM EST'
standup.startOfNext('hour').text; // 'Nov 16, 2026, 10:00 AM EST'
standup.startOfNext('wednesday').text; // 'Nov 18, 2026, 12:00 AM EST'
standup.next('wednesday').text; // 'Nov 18, 2026, 9:30 AM EST'

startOfPrevious()

dt.startOfPrevious(unit, firstDay?): DateTime

Moves back to the start of the calendar or clock unit before the one containing this moment, in this time zone. A weekday name in place of a unit gives the start of the previous day with that name, whereas previous() keeps the time of day.

unitUnit | Exclude<DayOfWeek, number>required

Calendar or clock unit from 'year' down to 'nanosecond', or a weekday name such as 'wednesday'.

firstDayDayOfWeek

First day of the week when unit is 'week'.

DateTime

A new DateTime at the start of the previous unit, or of the previous given weekday.

const standup = datetime('2026-11-16T09:30', 'America/New_York');

standup.startOfPrevious('day').text; // 'Nov 15, 2026, 12:00 AM EST'
standup.startOfPrevious('month').text; // 'Oct 1, 2026, 12:00 AM EDT'
standup.startOfPrevious('wednesday').text; // 'Nov 11, 2026, 12:00 AM EST'

next()

dt.next(target): DateTime

Moves forward to the next given weekday or MonthDay at the same time of day. When already on that weekday or annual date, it advances to the following occurrence.

targetDayOfWeek | MonthDayrequired

Weekday name such as 'friday', ISO number from 1 to 7, or recurring MonthDay.

DateTime

A new DateTime on the next matching date at the same local time.

import { datetime, monthDay } from 'native-dates';

const mon = datetime('2026-11-16T09:30', 'America/Los_Angeles');

mon.next('friday').day; // 20
mon.next('monday').day; // 23
mon.next(monthDay('12-25')).month; // 12

previous()

dt.previous(target): DateTime

Moves back to the most recent given weekday or MonthDay before this date, keeping the same time of day.

targetDayOfWeek | MonthDayrequired

Weekday name, three-letter prefix, ISO number from 1 to 7, or recurring MonthDay.

DateTime

A new DateTime on the previous matching date at the same local time.

const mon = datetime('2026-11-16T09:30', 'America/Los_Angeles');

mon.previous('friday').day; // 13
mon.previous(monthDay('10-31')).month; // 10

round()

dt.round(unit): DateTime
dt.round(increment, unit): DateTime

Rounds to the nearest unit or step increment, with half-way ties rounding up.

incrementnumber | Unitrequired

Step size that divides evenly into the next unit, or the target unit when rounding to 1.

unitUnit

Unit to round, from 'day' down to 'nanosecond'.

DateTime

A new rounded DateTime in the same time zone.

const stamp = datetime('2026-11-16T09:23:40', 'UTC');

stamp.round('hour').toString(); // '2026-11-16T09:00:00.000Z'
stamp.round(15, 'minutes').toString(); // '2026-11-16T09:30:00.000Z'

floor()

dt.floor(unit): DateTime
dt.floor(increment, unit): DateTime

Rounds down to the start of a unit or step increment. Accepts the same arguments as round().

datetime('2026-11-16T09:29:00Z').floor(15, 'minutes').toString(); // '2026-11-16T09:15:00.000Z'

ceil()

dt.ceil(unit): DateTime
dt.ceil(increment, unit): DateTime

Rounds up to the next unit or step increment. Accepts the same arguments as round().

datetime('2026-11-16T09:01:00Z').ceil(15, 'minutes').toString(); // '2026-11-16T09:15:00.000Z'

Comparing moments

Comparisons check when each moment happened, even if the two values use different time zones.

Comparing with ===

JavaScript’s === operator checks whether two variables point to the same object in memory. Call equals() to check whether two DateTime instances represent the same moment.

equals()

dt.equals(other): boolean

Returns true when both values represent the exact same instant, regardless of their time zones.

otherDateTimeInputrequired

Another DateTime or any input accepted by datetime().

boolean

true if both values point to the same instant.

const ny = datetime('2026-11-16T12:00', 'America/New_York');
const utc = datetime('2026-11-16T17:00Z', 'UTC');

ny.equals(utc); // true

isBefore()

dt.isBefore(other): boolean

Returns true if this moment is earlier than the other.

datetime('2026-11-16T16:59Z').isBefore('2026-11-16T17:00Z'); // true

isAfter()

dt.isAfter(other): boolean

Returns true if this moment is later than the other.

datetime('2026-11-16T17:01Z').isAfter('2026-11-16T17:00Z'); // true

isSame()

dt.isSame(other, unit?, firstDay?): boolean

Checks whether another moment falls in the same calendar or clock unit when both are viewed in this instance’s time zone. Calling isSame() without a unit checks exact instant equality.

otherDateTimeInputrequired

Moment to compare against, viewed in this instance's time zone.

unitUnit

Calendar or clock unit to compare, such as 'day' or 'month'.

firstDayDayOfWeek

First day of the week when unit is 'week'.

boolean

true when both moments fall in the same unit in this time zone.

const la = datetime('2026-11-16T09:30', 'America/Los_Angeles');
const lateUtc = datetime('2026-11-17T02:00Z', 'UTC');

la.isSame(lateUtc, 'day'); // true (6:00 PM Nov 16 in Los Angeles)
lateUtc.isSame(la, 'day'); // false (Nov 17 vs Nov 16 in UTC)

Calendar predicates

Zero-argument checks evaluated in the instance’s time zone:

Method Type Description
isPast(), isFuture() boolean Whether this instant is earlier or later than the current time.
isToday(), isTomorrow(), isYesterday() boolean Whether the local calendar date matches today, tomorrow, or yesterday in this zone.
isWeekday(), isWeekend() boolean Working day vs. weekend day in the active locale, such as Saturday and Sunday in en-US or Friday and Saturday in ar-SA.
isLeapYear() boolean Whether the local year is a leap year.

Measuring time

until()

dt.until(other): Duration
dt.until(other, unit): number

Measures the time from this moment to another, returning a negative span when the target is earlier. Pass a unit name to get the total length as a single number instead of a Duration.

otherDateTimeInputrequired

Target moment to measure toward.

unitUnit

Unit to return the total length in as a floating-point number.

Duration | number

A Duration counted in days and clock units, or a number when unit is given.

const doors = datetime('2026-11-16T08:00', 'America/Los_Angeles');
const standup = datetime('2026-11-16T09:30', 'America/Los_Angeles');

doors.until(standup).format('long', 'en-US'); // '1 hour, 30 minutes'
doors.until(standup, 'hours'); // 1.5

since()

dt.since(other): Duration
dt.since(other, unit): number

Measures the time elapsed since an earlier moment. Pass a unit name to get the total as a number.

const standup = datetime('2026-11-16T09:30', 'America/Los_Angeles');

standup.since('2026-11-16T08:00', 'minutes'); // 90

to()

dt.to(end): DateTimeRange
dt.to(count, unit): DateTimeRange
dt.for(length): DateTimeRange
dt.for(count, unit): DateTimeRange

Creates a half-open DateTimeRange starting at this moment and ending before the target moment or elapsed duration. Throws a RangeError if the end is earlier than the start. Use for() to pass an explicit duration length (refusing endpoints and unitless numbers).

endDateTimeInput | DurationInput | numberrequired

Target end moment, duration, or numeric count paired with unit.

unitUnit

Unit name when the first argument is a numeric count, such as 'hours' or 'days'.

DateTimeRange

A half-open DateTimeRange in this instance's time zone.

const standup = datetime('2026-11-16T09:30', 'America/Los_Angeles');

standup.to('2026-11-16T10:00').duration.minutes; // 30
standup.for(2, 'hours').end.hour; // 11

range()

dt.range(unit, firstDay?): DateTimeRange

Returns the half-open DateTimeRange for the calendar or clock unit containing this moment, from its start up to the start of the next unit.

unitUnitrequired

Calendar or clock unit from 'year' down to 'nanosecond'.

firstDayDayOfWeek

First day of the week when unit is 'week'.

DateTimeRange

A half-open DateTimeRange spanning unit in this time zone.

const event = datetime('2026-11-16T14:45', 'UTC');

event.range('day').toString();
// '2026-11-16T00:00:00.000Z/2026-11-17T00:00:00.000Z'

Formatting and conversion

format()

dt.format(spec?, locale?): string

Formats the date and time in its active zone using built-in presets, custom names from configure(), Intl options objects, or token patterns.

Localized presets from 'LT' through 'llll' are built in alongside [brackets] for literal words. See Formatting for the full preset and token reference.

specFormatSpecdefault 'medium'

Built-in or configured format name, Intl options object, or token pattern.

localestring

BCP 47 locale tag overriding this moment's or the configured locale for one call.

string

Formatted string in the instance's time zone.

const standup = datetime('2026-11-16T09:30', 'America/Los_Angeles');

standup.format('medium', 'en-US'); // 'Nov 16, 2026, 9:30 AM'
standup.format('full', 'en-US'); // 'Monday, November 16, 2026 at 9:30 AM'
standup.format('LLL', 'en-US'); // 'November 16, 2026 at 9:30 AM'
standup.format('text', 'en-US'); // 'Nov 16, 2026, 9:30 AM PST'
standup.format('YYYY-MM-DD HH:mm'); // '2026-11-16 09:30'
standup.format('MMM D [at] h:mm a', 'en-US'); // 'Nov 16 at 9:30 am'
standup.format(
  { weekday: 'short', hour: '2-digit', minute: '2-digit' },
  'de-DE',
); // 'Mo., 09:30'

from()

dt.from(other?, locale?): string
dt.formatRelative(other?, locale?): string

Formats the elapsed distance from another moment to this one as a localized phrase via Intl.RelativeTimeFormat, such as '3 hours ago' or 'in 2 days'.

Omitting the first argument compares against the current moment, and formatRelative() works as an alias. Zero seconds prints 'now', while days, months, and years use numeric counts rather than calendar words like yesterday.

otherDateTimeInput

Reference moment to measure from, interpreted in this instance's time zone when unzoned. Defaults to the current moment.

localeLocale

BCP 47 locale tag overriding this moment's or the configured locale for one call.

string

Localized relative phrase.

const anchor = datetime('2026-11-16T12:00', 'UTC');

anchor.from(anchor, 'en-US'); // 'now'
anchor.minus(3, 'hours').from(anchor, 'en-US'); // '3 hours ago'
anchor.minus(23, 'hours').from(anchor, 'en-US'); // '1 day ago'
anchor.plus(45, 'minutes').from(anchor, 'en-US'); // 'in 1 hour'
anchor.minus(3, 'hours').from(anchor, 'es'); // 'hace 3 horas'

fromNow()

dt.fromNow(locale?): string

Formats how far this moment is from right now as a localized phrase, equivalent to calling from() with no reference moment.

localeLocale

BCP 47 locale tag overriding this moment's or the configured locale for one call.

string

Localized relative phrase measured from now.

now().minus(5, 'minutes').fromNow('en-US'); // '5 minutes ago'
now().plus(2, 'hours').fromNow('en-US'); // 'in 2 hours'

formatRelative()

dt.formatRelative(other?, locale?): string

Alias for from() that formats the elapsed distance from other, or from now when omitted, as a localized phrase.

locale()

dt.locale(): Locale | undefined
dt.locale(tag): DateTime

Reads the locale carried on this moment, or returns a copy that formats and starts weeks in another locale across presets, week boundaries, and derived values. Underscore tags and Accept-Language headers normalize automatically, an empty tag clears it, and lang() is an alias.

tagLocale | null | undefined

Locale tag, tag array, or Accept-Language header to carry forward, or null to clear it.

DateTime | Locale | undefined

The active tag when called with no arguments, or a new DateTime carrying tag.

const standup = datetime('2026-11-16T09:30', 'Europe/Berlin').locale('es-ES');

standup.locale(); // 'es-ES'
standup.plus(1, 'week').date.format('long'); // '23 de noviembre de 2026'
standup.locale(null).locale(); // undefined

lang()

dt.lang(): Locale | undefined
dt.lang(tag): DateTime

Shorthand alias for locale() that reads or attaches a BCP 47 locale tag on this moment.

as()

dt.as('datetime'): DateTime
dt.as('date'): CalendarDate
dt.as('time'): Time
dt.as('yearMonth'): YearMonth
dt.as('monthDay'): MonthDay

Converts this moment to another kind inside a method chain without stopping for property access, including YearMonth and MonthDay values in its active time zone.

kind'datetime' | 'date' | 'time' | 'yearMonth' | 'monthDay'required

Target kind to read this moment as in its active time zone.

DateTime | CalendarDate | Time | YearMonth | MonthDay

Converted value in this instance's time zone.

const standup = datetime('2026-11-16T09:30', 'America/Los_Angeles');

standup.in('Asia/Tokyo').as('date').toString(); // '2026-11-17'
standup.in('Asia/Tokyo').as('time').toString(); // '02:30:00'
standup.as('yearMonth').toString(); // '2026-11'
standup.as('monthDay').toString(); // '11-16'

toString()

dt.toString(): string
dt.toJSON(): string

Returns the instant as a UTC ISO 8601 string, suitable for databases, URLs, and network payloads. toJSON() returns the same string for JSON.stringify().

string

UTC ISO 8601 timestamp, such as '2026-11-16T17:30:00.000Z'.

const standup = datetime('2026-11-16T09:30', 'America/Los_Angeles');

standup.toString(); // '2026-11-16T17:30:00.000Z'
JSON.stringify({ standup }); // '{"standup":"2026-11-16T17:30:00.000Z"}'

toJSDate()

dt.toJSDate(): Date

Returns a native JavaScript Date for the same instant.

toTemporal()

dt.toTemporal(): Temporal.ZonedDateTime

Returns the underlying Temporal.ZonedDateTime instance.

valueOf()

dt.valueOf(): number

Returns epoch milliseconds so two DateTime values can be subtracted or compared with numeric operators.

Edit this pageUpdated Nov 20, 2026