ts-time/LocalDateTime

Consumption

import LocalDateTime from "ts-time/LocalDateTime";

Default export#

Hierarchy#

  • class LocalDateTime

Description#

Comprises a specific date/time, without time zone relation. In other words, this is a tuple of (LocalDate, LocalTime).
Construct#

A common way to construct an object in ts-time is to call its of* static method. For example, the following LocalDateTime instances represent 18 hours, 30 minutes, 15 seconds, 225 milliseconds on 15th of February, 2022:

LocalDateTime.ofComponents(2022, FEBRUARY, 15, 18, 30, 15, 225);
LocalDateTime.ofComponents(2022, 2, 15, 18, 30, 15, 225);

As opposed to Java API, there's no common way to get the current instance of LocalDateTime in ts-time, because ts-time doesn't have a concept of default time zone. Instead, you must get the current Instant and convert it to an object that you need, taking time zone into consideration.

Instant.now().atZone(UTC).dateTime;             // Current LocalDateTime in UTC
Instant.now().atZone(LOCAL_ZONE_ID).dateTime;   // Current LocalDateTime in the local time zone
Instant.now().atZone(zone).dateTime;            // Current LocalDateTime in a given ZoneId/ZoneOffset

It makes ts-time API more robust. It leaves less room for a mistake.

A common way to convert a native JavaScript Date object to a ts-time object is to call fromNative* static method:

LocalDateTime.fromNativeUtc(date);              // LocalDateTime from a given Date in UTC
LocalDateTime.fromNativeLocal(date);            // LocalDateTime from a given Date in the local time zone
Instant.fromNative(date).atZone(zone).dateTime; // LocalDateTime from a given Date in a given ZoneId/ZoneOffset

You can convert instances of other ts-time classes to LocalDateTime via their properties and methods:

LocalDateTime.of(date, time);                   // From a pair of LocalDate and LocalTime
date.atTime(time);                              // Equivalent
instant.atZone(zone).dateTime;                  // From Instant in a given ZoneId/ZoneOffset
offsetDateTime.dateTime;                        // From OffsetDateTime in the same ZoneOffset
zonedDateTime.dateTime;                         // From ZonedDateTime in the same ZoneId

Please notice that conversions from OffsetDateTime and ZonedDateTime result in a partial data loss (offset and time zone respectively).

Another sophisticated constructor: ofEpochMsUtc. Also check sophisticated constructors of LocalDate and LocalTime, as LocalDateTime is essentially a pair of them.

Parse#

A common way to parse an ISO 8601 compliant string in ts-time is to call parse static method. For example, the following LocalDateTime instance represents 18 hours, 30 minutes, 15 seconds, 225 milliseconds on 15th of February, 2022:

LocalDateTime.parse("2022-02-15T18:30:15.225");

The library doesn't yet support parsing non-compliant strings.

Inspect#

In the following example, we inspect various properties of a LocalDateTime object. Please notice the difference in return value types:

const dateTime       = LocalDateTime.ofComponents(2022, FEBRUARY, 15, 18, 30, 15, 225);
const year           = dateTime.year;            // 2022
const month          = dateTime.month;           // FEBRUARY
const monthValue     = dateTime.month.value;     // 2
const dayOfMonth     = dateTime.dayOfMonth;      // 15
const dayOfWeek      = dateTime.dayOfWeek;       // TUESDAY
const dayOfWeekValue = dateTime.dayOfWeek.value; // 2
const hour           = dateTime.hour;            // 18
const minute         = dateTime.minute;          // 30
const second         = dateTime.second;          // 15
const ms             = dateTime.ms;              // 225

Other sophisticated features for LocalDateTime inspection: epochMsUtc, era, yearOfEra, weekBasedYear, weekOfWeekBasedYear, dayOfYear, dayOfWeekBasedYear, epochDay, quarterOfYear, isLeapYear, lengthOfYear.

Compare#

A common way to compare objects in ts-time is to call equals, isBefore, isAfter, compareTo methods:

const d1 = LocalDateTime.ofComponents(2022, FEBRUARY, 15, 18, 30, 15, 225);
const d2 = LocalDateTime.ofComponents(2022, FEBRUARY, 15, 18, 30, 15, 226);
d1.equals(d2);    // false
d1.isBefore(d2);  // true
d1.isAfter(d2);   // false
d1.compareTo(d2); // -1

For nullable objects, use static methods instead. Null and undefined are considered less than anything, except each other:

const d1: LocalDateTime = null;
const d2 = LocalDateTime.ofComponents(2022, FEBRUARY, 15, 18, 30, 15, 226);
LocalDateTime.equal(d1, d2);     // false
LocalDateTime.isBefore(d1, d2);  // true
LocalDateTime.isAfter(d1, d2);   // false
LocalDateTime.compare(d1, d2);   // -1
Manipulate#

Every object in ts-time is immutable. Therefore every manipulation returns a new object.

To add/subtract a Period, call plusPeriod/minusPeriod method:

const dateTime = LocalDateTime.ofComponents(2022, FEBRUARY, 15, 18, 30, 15, 225);
const d1 = dateTime.plusPeriod(DAY_PERIOD);                // 18:30:15.225 on 16th of February, 2022
const d2 = dateTime.plusPeriod(Period.ofDays(2));          // 18:30:15.225 on 17th of February, 2022
const d3 = dateTime.minusPeriod(MONTH_PERIOD);             // 18:30:15.225 on 15th of January, 2022

To add/subtract a duration, call plusDuration/minusDuration method:

const dateTime = LocalDateTime.ofComponents(2022, FEBRUARY, 15, 18, 30, 15, 225);
const d1 = dateTime.plusDuration(MINUTE_DURATION);         // 18:31:15.225 on 15th of February, 2022
const d2 = dateTime.plusDuration(Duration.ofHours(10));    // 04:30:15.225 on 16th of February, 2022
const d3 = dateTime.minusDuration(Duration.ofSeconds(30)); // 18:29:45.225 on 15th of February, 2022

For difference between Period and Duration, see their documentation. For LocalDateTime, they are interchangeable - apart for the list of supported date/time components.

To change one of the components, preserving all the rest, call with* methods:

const dateTime = LocalDateTime.ofComponents(2022, FEBRUARY, 15, 18, 30, 15, 225);
const d1 = dateTime.withYear(2025);                        // 18:30:15.225 on 15th of February, 2025
const d2 = dateTime.withMonth(APRIL);                      // 18:30:15.225 on 15th of April, 2022
const d3 = dateTime.withDayOfMonth(10);                    // 18:30:15.225 on 10th of February, 2022
const d4 = dateTime.withDayOfWeek(SUNDAY);                 // 18:30:15.225 on 20th of February, 2022, Sunday
const d5 = dateTime.withHour(20);                          // 20:30:15.225 on 15th of February, 2022
const d6 = dateTime.withMinute(20);                        // 18:20:15.225 on 15th of February, 2022
const d7 = dateTime.withSecond(20);                        // 18:30:20.225 on 15th of February, 2022
const d8 = dateTime.withMs(20);                            // 18:30:15.020 on 15th of February, 2022

To truncate all the least-significant components, call truncate* methods:

const dateTime = LocalDateTime.ofComponents(2022, FEBRUARY, 15, 18, 30, 15, 225);
const d1 = dateTime.truncateToYear;                        // Midnight on 1st of January, 2022
const d2 = dateTime.truncateToMonth;                       // Midnight on 1st of February, 2022
const d3 = dateTime.truncateToWeek;                        // Midnight on 14th of February, 2022, Monday
const d4 = dateTime.truncateToDay;                         // Midnight on 15th of February, 2022
const d5 = dateTime.truncateToHour;                        // 18:00:00.000 on 15th of February, 2022
const d6 = dateTime.truncateToMinute;                      // 18:30:00.000 on 15th of February, 2022
const d7 = dateTime.truncateToSecond;                      // 18:30:15.000 on 15th of February, 2022

The library doesn't yet support Sunday as the 1st day of the week. But there's a workaround:

const d8 = dateTime.truncateToDay.minusPeriod(Period.ofDays(dateTime.dayOfWeek.value % 7)); // Midnight on 13th of February, 2022, Sunday

Or a flexible solution, where firstDayOfWeek is 1 for Monday, and 7 for Sunday:

const d8 = dateTime.truncateToDay.minusPeriod(Period.ofDays((dateTime.dayOfWeek.value + 7 - firstDayOfWeek) % 7));

Other sophisticated features for LocalDateTime manipulation: withDayOfYear, truncateToWeekBasedYear.

Convert#

You can convert LocalDateTime to other kinds of objects via its properties and methods:

const dateTime = LocalDateTime.ofComponents(2022, FEBRUARY, 15, 18, 30, 15, 225);
dateTime.date;                 // To LocalDate: 2022-02-15
dateTime.time;                 // To LocalTime: 18:30:15.225
dateTime.atOffset(offset);     // To OffsetDateTime in a given ZoneOffset: 2022-02-15T18:30:15.225+01:00
dateTime.atZone(zone);         // To ZonedDateTime in a given ZoneId: 2022-02-15T18:30:15.225+01:00[Europe/Berlin]
dateTime.atZone(zone).instant; // To Instant in a given ZoneId/ZoneOffset: 2022-02-15T17:30:15.225Z

Please notice that - when converting to Instant - string presentation may change depending on the selected time zone.

In order to convert LocalDateTime from one ZoneId/ZoneOffset to another, you must first convert it to an Instant:

dateTime.atZone(sourceZone).instant.atZone(targetZone).dateTime;

You can as well convert LocalDateTime to a native JavaScript Date:

const dateTime = LocalDateTime.ofComponents(2022, FEBRUARY, 15, 18, 30, 15, 225);
dateTime.nativeUtc;            // Date representing 18:30:15.225 on 15th of February, 2022 in UTC
dateTime.nativeLocal;          // Date representing 18:30:15.225 on 15th of February, 2022 in the local time zone
dateTime.atZone(zone).native;  // Date representing 18:30:15.225 on 15th of February, 2022 in a given ZoneId/ZoneOffset

For backward conversion, see Construct.

Format#

Every class in ts-time has ISO 8601 compliant toString method:

const dateTime = LocalDateTime.ofComponents(2022, FEBRUARY, 15, 18, 30, 15, 225);
dateTime.toString(); // "2022-02-15T18:30:15.225"

For more sophisticated string formatting, add ts-time-format library to your list of dependencies:

npm install --save ts-time-format

Now you can construct an instance of DateTimeFormatter in order to format arbitrary LocalDateTime instances:

const formatter = DateTimeFormatter.ofPattern("dd.MMM''yy, hh:mm a");
const dateTime = LocalDateTime.ofComponents(2022, FEBRUARY, 15, 18, 30, 15, 225);
formatter.format(dateTime); // "15.Feb'22, 06:30 PM"

You can define a custom context object to internationalize the formatted strings:

const context = {monthShortNames: ["Янв", "Фев", "Мар"]};
formatter.format(dateTime, context); // "15.Фев'22, 06:30 PM"

Fields#

date#

readonly date: LocalDate

Date part.
time#

readonly time: LocalTime

Time part.
nativeLocal#

readonly nativeLocal: Date

Native JS Date representing this local date/time in the browser time zone, for compatibility with native and third party API.
nativeUtc#

readonly nativeUtc: Date

Native JS Date representing this local date/time in UTC, for compatibility with native and third party API.
epochMsUtc#

readonly epochMsUtc: number

Number of milliseconds since epoch in UTC.
era#

readonly era: Era

Era of this local date/time.
year#

readonly year: number

Absolute year.
yearOfEra#

readonly yearOfEra: number

Year of era. See Era for details.
weekBasedYear#

readonly weekBasedYear: number

Absolute week based year.

By definition, the 1st week of week based year contains the 1st Thursday of the year, and the week based year starts from the Monday of this week.

month#

readonly month: Month

Month.
weekOfWeekBasedYear#

readonly weekOfWeekBasedYear: number

1-based week of week-based year.

By definition, the 1st week of week based year contains the 1st Thursday of the year, and the week based year starts from the Monday of this week.

dayOfYear#

readonly dayOfYear: number

1-based day of year.
dayOfWeekBasedYear#

readonly dayOfWeekBasedYear: number

1-based day of week-based year.

By definition, the 1st week of week based year contains the 1st Thursday of the year, and the week based year starts from the Monday of this week.

dayOfMonth#

readonly dayOfMonth: number

1-based day of month.
dayOfWeek#

readonly dayOfWeek: DayOfWeek

Day of week.
epochDay#

readonly epochDay: number

1-based day since epoch (i.e. 1st of JANUARY 1970 is the 1st epoch day).
quarterOfYear#

readonly quarterOfYear: number

1-based quarter of year.
isLeapYear#

readonly isLeapYear: boolean

True if this is a leap year.
lengthOfYear#

readonly lengthOfYear: number

Number of days in this year (365 for non-leap, 366 for leap).
hour#

readonly hour: number

Hour of a day (0-23).
minute#

readonly minute: number

Minute of an hour (0-59).
second#

readonly second: number

Second of a minute (0-59).
ms#

readonly ms: number

Millisecond of a second (0-999).
truncateToYear#

readonly truncateToYear: LocalDateTime

Start of the year (i.e. the 1st of JANUARY, MIDNIGHT).
truncateToWeekBasedYear#

readonly truncateToWeekBasedYear: LocalDateTime

Start of the week-based year (i.e. MONDAY, MIDNIGHT).

By definition, the 1st week of week based year contains the 1st Thursday of the year, and the week based year starts from the Monday of this week.

truncateToMonth#

readonly truncateToMonth: LocalDateTime

Start of the month (i.e. 1st day of one, MIDNIGHT).
truncateToWeek#

readonly truncateToWeek: LocalDateTime

Start of the week (i.e. Monday, MIDNIGHT).
truncateToDay#

readonly truncateToDay: LocalDateTime

Start of the day (i.e. MIDNIGHT).
truncateToHour#

readonly truncateToHour: LocalDateTime

Start of the hour (i.e. 0 minutes, 0 seconds, 0 milliseconds).
truncateToMinute#

readonly truncateToMinute: LocalDateTime

Start of the minute (i.e. 0 seconds, 0 milliseconds).
truncateToSecond#

readonly truncateToSecond: LocalDateTime

Start of the second (i.e. 0 milliseconds).

Methods#

compareTo#

(other: LocalDateTime): number

other
Local date/time to compare to.
returns
  • 0 if this is the same local date/time;
  • positive value if this local date/time goes after other;
  • negative value if this local date/time goes before other.
Null and undefined are considered less than anything, except each other.

Note that a method call on null or undefined always leads to an error. So, if your variable may contain null or undefined, use the respective static method instead.

equals#

(other: LocalDateTime): boolean

other
Local date/time to compare to.
returns
True if this local date/time is equal to other. Null and undefined are only equal to each other.

Note that a method call on null or undefined always leads to an error. So, if your variable may contain null or undefined, use the respective static method instead.

isBefore#

(other: LocalDateTime): boolean

other
Local date/time to compare to.
returns
True if this local date/time goes before other. Null and undefined go before anything, except each other.

Note that a method call on null or undefined always leads to an error. So, if your variable may contain null or undefined, use the respective static method instead.

isAfter#

(other: LocalDateTime): boolean

other
Local date/time to compare to.
returns
True if this local date/time goes after other. Null and undefined go before anything, except each other.

Note that a method call on null or undefined always leads to an error. So, if your variable may contain null or undefined, use the respective static method instead.

atZone#

(zone: ZoneId): ZonedDateTime

zone
Time zone.
returns
This date/time in the specified time zone.
atOffset#

(offset: ZoneOffset): OffsetDateTime

zone
Time zone offset.
returns
This date/time in the specified time zone offset.
plusDuration#

(duration: Duration): LocalDateTime

duration
Duration to add.
returns
New LocalDateTime shifted onwards from this one by the specified duration.
plusPeriod#

(period: Period): LocalDateTime

period
Period to add.
returns
New LocalDateTime shifted onwards from this one by the specified period.
minusDuration#

(duration: Duration): LocalDateTime

duration
Duration to subtract.
returns
New LocalDateTime shifted backwards from this one by the specified duration.
minusPeriod#

(period: Period): LocalDateTime

period
Period to subtract.
returns
New LocalDateTime shifted backwards from this one by the specified period.
withYear#

(year: number): LocalDateTime

year
Absolute year.
returns
New LocalDateTime with the specified year and its current month/day of month/time. If such date doesn't exist, it shifts the date back to the nearest valid one, preserving the time (e.g. 29th of FEBRUARY in 2019, 18:30 gets shifted to 28th of FEBRUARY, 18:30).
withMonth#

(month: number | Month): LocalDateTime

month
Month.
returns
New LocalDateTime with the specified month and its current year/day of month/time. If such date doesn't exist, it shifts the date back to the nearest valid one, preserving the time (e.g. 31st of APRIL, 18:30 gets shifted to 30th of APRIL, 18:30).
withDayOfMonth#

(dayOfMonth: number): LocalDateTime

dayOfMonth
1-based day of month.
returns
New LocalDateTime with the specified day of month and its current year/month/time.
withDayOfWeek#

(dayOfWeek: number | DayOfWeek): LocalDateTime

dayOfWeek
Day of week or its numeric value
returns
New LocalDateTime with the specified day of week and its current week/time.
withDayOfYear#

(dayOfYear: number): LocalDateTime

dayOfYear
1-based day of year.
returns
New LocalDateTime with the specified day of year and its current year/time.
withHour#

(hour: number): LocalDateTime

hour
Hour of a day.
returns
New LocalDateTime with the specified hour of a day. All other properties don't change.
withMinute#

(minute: number): LocalDateTime

minute
Minute of an hour.
returns
New LocalDateTime with the specified minute of an hour. All other properties don't change.
withSecond#

(second: number): LocalDateTime

second
Second of a minute.
returns
New LocalDateTime with the specified second of a minute. All other properties don't change.
withMs#

(ms: number): LocalDateTime

ms
Millisecond of a second.
returns
New LocalDateTime with the specified millisecond of a second. All other properties don't change.
toString#

(): string

returns
String representation of the date/time in ISO format, such as "2019-12-30T18:30:15.225".

Static methods#

of#

(date: LocalDate, time: LocalTime): LocalDateTime

date
Date part.
time
Time part.
returns
New LocalDateTime with the specified parts.
ofComponents#

(year: number, month: number | Month = JANUARY, dayOfMonth: number = 1, hour: number = 0, minute: number = 0, second: number = 0, ms: number = 0): LocalDateTime

year
Absolute year.
month
Month or its numeric value.
dayOfMonth
1-based day of month.
hour
Hour of day.
minute
Minute of hour.
second
Second of minute.
ms
Millisecond of second.
returns
LocalDateTime representation.
ofEpochMsUtc#

(ms: number): LocalDateTime

ms
Number of milliseconds since epoch in UTC.
returns
LocalDateTime representation.
fromNativeLocal#

(date: Date): LocalDateTime

date
Native JS date.
returns
LocalDateTime representation of date in the browser time zone, for compatibility with native and third party API.
fromNativeUtc#

(date: Date): LocalDateTime

date
Native JS date.
returns
LocalDateTime representation of date in UTC, for compatibility with native and third party API.
parse#

(str: string): LocalDateTime throws TemporalParsingError

str
String representation of a local date/time in ISO format, such as '2019-12-30T18:30:15.225'.
returns
LocalDateTime representation.
compare#

(x: LocalDateTime, y: LocalDateTime): number

x
One local date/time.
y
Another local date/time.
returns
  • 0 if this x and y are the same local date/time;
  • positive value if x goes after y;
  • negative value if x goes before y.
Null and undefined are considered less than anything, except each other.
equal#

(x: LocalDateTime, y: LocalDateTime): boolean

x
One local date/time.
y
Another local date/time.
returns
True if x is equal to y. Null and undefined are only equal to each other.
isBefore#

(x: LocalDateTime, y: LocalDateTime): boolean

x
One local date/time.
y
Another local date/time.
returns
True if x goes before y. Null and undefined go before anything, except each other.
isAfter#

(x: LocalDateTime, y: LocalDateTime): boolean

x
One local date/time.
y
Another local date/time.
returns
True if x goes after y. Null and undefined go before anything, except each other.