js-joda
Advanced tools
Comparing version 1.9.2 to 1.9.3
@@ -6,2 +6,9 @@ Changelog | ||
### 1.9.3 | ||
* fix typescript definitions: add `ZoneId#id()` #265 | ||
* fix typescript definitions: Fix DateTimeFormatter.withLocale() #277 | ||
* Remove unreachable code #278 | ||
* add package-lock for dev dependencies | ||
### 1.9.2 | ||
@@ -8,0 +15,0 @@ |
@@ -1,7 +0,6 @@ | ||
js-joda Cheat sheet | ||
============================================= | ||
# js-joda cheat sheet | ||
[For a detailed API Reference refer to the ESDoc generated docs](//js-joda.github.io/js-joda/esdoc/) | ||
For a detailed API Reference refer to the [ESDoc generated docs](./esdoc/). | ||
## Table of content | ||
## Table of contents | ||
@@ -14,117 +13,123 @@ <!-- toc --> | ||
- [LocalDate](#localdate) | ||
* [Create a LocalDate](#create-a-localdate) | ||
* [Get values from LocalDate](#get-values-from-localdate) | ||
* [Get weeks of week based year, get year quarters and the day of quarter](#get-weeks-of-week-based-year-get-year-quarters-and-the-day-of-quarter) | ||
* [Adding to/ subtracting from a LocalDate](#adding-to-subtracting-from-a-localdate) | ||
* [Alter certain fields of a LocalDate](#alter-certain-fields-of-a-localdate) | ||
* [Compare LocalDates](#compare-localdates) | ||
* [Distance on the timeline](#distance-on-the-timeline) | ||
* [Converting from and to other temporals](#converting-from-and-to-other-temporals) | ||
* [Adjust a date to another date](#adjust-a-date-to-another-date) | ||
- [Create a LocalDate](#create-a-localdate) | ||
- [Get values from LocalDate](#get-values-from-localdate) | ||
- [Get weeks of week based year, get year quarters and the day of quarter](#get-weeks-of-week-based-year-get-year-quarters-and-the-day-of-quarter) | ||
- [Adding to/ subtracting from a LocalDate](#adding-to-subtracting-from-a-localdate) | ||
- [Alter certain fields of a LocalDate](#alter-certain-fields-of-a-localdate) | ||
- [Compare LocalDates](#compare-localdates) | ||
- [Distance on the timeline](#distance-on-the-timeline) | ||
- [Converting from and to other temporals](#converting-from-and-to-other-temporals) | ||
- [Adjust a date to another date](#adjust-a-date-to-another-date) | ||
- [LocalTime](#localtime) | ||
* [Create a LocalTime instance](#create-a-localtime-instance) | ||
* [Get values from LocalTime](#get-values-from-localtime) | ||
* [Adding to/ subtracting from a LocalTime instance](#adding-to-subtracting-from-a-localtime-instance) | ||
* [Alter certain fields of a LocalTime instance](#alter-certain-fields-of-a-localtime-instance) | ||
* [Truncate a LocalTime instance](#truncate-a-localtime-instance) | ||
* [Compare LocalTime instances](#compare-localtime-instances) | ||
* [Distance between times](#distance-between-times) | ||
* [Convert a LocalTime from a javascript Date or moment](#convert-a-localtime-from-a-javascript-date-or-moment) | ||
- [Create a LocalTime instance](#create-a-localtime-instance) | ||
- [Get values from LocalTime](#get-values-from-localtime) | ||
- [Adding to/ subtracting from a LocalTime instance](#adding-to-subtracting-from-a-localtime-instance) | ||
- [Alter certain fields of a LocalTime instance](#alter-certain-fields-of-a-localtime-instance) | ||
- [Truncate a LocalTime instance](#truncate-a-localtime-instance) | ||
- [Compare LocalTime instances](#compare-localtime-instances) | ||
- [Distance between times](#distance-between-times) | ||
- [Convert a LocalTime from a javascript Date or moment](#convert-a-localtime-from-a-javascript-date-or-moment) | ||
- [LocalDateTime](#localdatetime) | ||
* [Create a LocalDateTime instance](#create-a-localdatetime-instance) | ||
* [Get values from LocalDateTime](#get-values-from-localdatetime) | ||
* [Adding to/ subtracting from a LocalDateTime instance](#adding-to-subtracting-from-a-localdatetime-instance) | ||
* [Alter certain fields of a LocalDateTime instance](#alter-certain-fields-of-a-localdatetime-instance) | ||
* [Truncate a LocalDateTime instance](#truncate-a-localdatetime-instance) | ||
* [Compare LocalDateTime instances](#compare-localdatetime-instances) | ||
* [Distance between local dates and times](#distance-between-local-dates-and-times) | ||
* [Convert from a javascript Date or moment](#convert-from-a-javascript-date-or-moment) | ||
- [Create a LocalDateTime instance](#create-a-localdatetime-instance) | ||
- [Get values from LocalDateTime](#get-values-from-localdatetime) | ||
- [Adding to/ subtracting from a LocalDateTime instance](#adding-to-subtracting-from-a-localdatetime-instance) | ||
- [Alter certain fields of a LocalDateTime instance](#alter-certain-fields-of-a-localdatetime-instance) | ||
- [Truncate a LocalDateTime instance](#truncate-a-localdatetime-instance) | ||
- [Compare LocalDateTime instances](#compare-localdatetime-instances) | ||
- [Distance between local dates and times](#distance-between-local-dates-and-times) | ||
- [Convert from a javascript Date or moment](#convert-from-a-javascript-date-or-moment) | ||
- [ZonedDateTime](#zoneddatetime) | ||
* [The system default time zone](#the-system-default-time-zone) | ||
* [Iana tzdb support](#iana-tzdb-support) | ||
* [Create a ZonedDateTime](#create-a-zoneddatetime) | ||
* [Switch timezones](#switch-timezones) | ||
* [Get and manipulate values from a ZonedDateTime](#get-and-manipulate-values-from-a-zoneddatetime) | ||
- [The system default time zone](#the-system-default-time-zone) | ||
- [Iana tzdb support](#iana-tzdb-support) | ||
- [Create a ZonedDateTime](#create-a-zoneddatetime) | ||
- [Switch timezones](#switch-timezones) | ||
- [Get and manipulate values from a ZonedDateTime](#get-and-manipulate-values-from-a-zoneddatetime) | ||
- [Period](#period) | ||
- [Duration](#duration) | ||
- [Customize js-joda](#customize-js-joda) | ||
* [Custom temporal adjuster](#custom-temporal-adjuster) | ||
* [Custom temporal fields and temporal units](#custom-temporal-fields-and-temporal-units) | ||
* [Custom formatter and queries](#custom-formatter-and-queries) | ||
- [Custom temporal adjuster](#custom-temporal-adjuster) | ||
- [Custom temporal fields and temporal units](#custom-temporal-fields-and-temporal-units) | ||
- [Custom formatter and queries](#custom-formatter-and-queries) | ||
<!-- tocstop --> | ||
## Try it out | ||
--- | ||
Tip: Try out the cheat sheet examples in your browser console. All js-joda classes are imported into the global name space of [the js-joda webpage](http://js-joda.github.io/js-joda/cheat-sheet.html). | ||
## General concepts | ||
## Consistent method prefixes | ||
The API is **immutable**. An existing instance is never changed. All manipulating methods (`plus`, `at`, etc.) return new instances. | ||
The API is using a set of consistent method prefixes. | ||
**An existing instance is always valid**. If you try to create an invalid value, you'll get an exception instead of a `null` or `undefined` value. | ||
- of - static factory method | ||
- parse - static factory method focused on parsing | ||
- is - checks if something is true | ||
- with - the immutable equivalent of a setter | ||
- plus - adds an amount to an object | ||
- minus - subtracts an amount from an object | ||
- to - converts this object to another type | ||
- at - combines this object with another, such as date.atTime(time) | ||
- getter methods for instance properties are omitting the get keyword, e.q. localDate.year() | ||
### Method naming conventions | ||
## Basic concepts | ||
The API uses consistently named methods. | ||
The API is immutable, an existing instance is never changed, all manipulating methods as parse/ with/ plus/ minus/ to/ at are returning new instances. | ||
An existing instance is always valid. Instead of returning null or invalid values, exceptions are thrown. | ||
| method name or prefix | usage | examples | | ||
| --------------------- | -------------------------------------------- | --------------------------------------------------------------- | | ||
| `.of` | static factory method for building by parts | `LocalDate.of(2016, 2, 23)` <br> `LocalDate.ofInstant(i)` | | ||
| `.parse` | static factory method for parsing strings | `LocalDate.parse('2016-02-23')` <br> `LocalTime.parse('12:34')` | | ||
| `.is` | checks for certain conditions | `t1.isAfter(t2)` <br> `d1.isLeapYear()` | | ||
| `.equals` | checks for equivalence between two instances | `t1.equals(t2)` | | ||
| `.with` | the immutable equivalent of a setter | `d.withDayOfMonth(1)` <br> `t.withHour(9)` | | ||
| `.plus` | adds an amount to an object | `t.plusMinutes(5)` <br> `d.plus(3, ChronoUnit.YEARS)` | | ||
| `.minus` | subtracts an amount from an object | `t.minusHours(1)` <br> `d.minus(1, ChronoUnit.DAYS)` | | ||
| `.to` | converts this object to another type | `dt.toLocalDate()` <br> `d1.until(d2).toTotalMonths()` | | ||
| `.at` | combines one object with another | `date.atTime(time)` <br> `localDate.atZone(tz)` | | ||
Note that getter methods for instance properties omit the get keyword: `d.year()`, not ~~`d.getYear()`~~. | ||
### Try it out | ||
**Tip:** You can run the examples on this page in your browser console. All `js-joda` classes are imported into the global namespace of this web page. | ||
![image](https://user-images.githubusercontent.com/2136620/47266364-9be10b00-d535-11e8-9a38-b53a6c16728d.png) | ||
## LocalDate | ||
A LocalDate represents a date without a time and time-zone in the ISO-8601 calendar system, such as 2007-12-24. | ||
A `LocalDate` represents a date with **no time** and **no time zone** in the [ISO-8601](https://en.wikipedia.org/wiki/ISO_8601) calendar system, such as 2007-12-24. | ||
### Create a LocalDate | ||
### Create a `LocalDate` | ||
```javascript | ||
// obtain the current date in the system default timezone, e.g. 2016-02-23 | ||
// obtain the current date in the system default time zone, e.g. 2016-02-23 | ||
LocalDate.now(); | ||
// obtain the current date in the utc timezone, e.g. 2016-02-23 | ||
// obtain the current date in the UTC time zone, e.g. 2016-02-23 | ||
LocalDate.now(ZoneOffset.UTC); | ||
// obtain an instance of LocalDate from an ISO8601 formatted text string | ||
// obtain an instance of LocalDate from an ISO 8601 formatted text string | ||
LocalDate.parse('2016-02-23'); | ||
// obtain an instance of LocalDate from a year, month, and dayOfMonth value | ||
LocalDate.of(2016, 2, 23) // 2016-02-23 | ||
LocalDate.of(2016, 2, 23); // 2016-02-23 | ||
// obtain an instance of LocalDate from a year, month, and dayOfMonth value | ||
LocalDate.of(2016, Month.FEBRUARY, 23) // 2016-02-23 | ||
LocalDate.of(2016, Month.FEBRUARY, 23); // 2016-02-23 | ||
// obtain an instance of LocalDate from am epochDay where day 0 is 1970-01-01 | ||
LocalDate.ofEpochDay(-1) // 1969-12-31 | ||
// obtain an instance of LocalDate from an epochDay where day 0 is 1970-01-01 | ||
LocalDate.ofEpochDay(-1); // 1969-12-31 | ||
// obtain an instance of LocalDate from am epochDay where day 0 is 1970-01-01 | ||
LocalDate.ofYearDay(2016, 42) // 2016-02-11 | ||
// obtain an instance of LocalDate from an epochDay where day 0 is 1970-01-01 | ||
LocalDate.ofYearDay(2016, 42); // 2016-02-11 | ||
``` | ||
### Get values from LocalDate | ||
### Get values from `LocalDate` | ||
```javascript | ||
var d = LocalDate.parse('2016-12-24'); | ||
d.toString(); // '2016-12-24' ISO8601 format | ||
d.toString(); // '2016-12-24' ISO 8601 format | ||
d.dayOfMonth(); // 24 | ||
d.month(); // Month.DECEMBER | ||
d.month(); // Month.DECEMBER | ||
d.monthValue(); // 12 | ||
d.year(); // 2016 | ||
d.year(); // 2016 | ||
d.dayOfWeek(); // DayOfWeek.SATURDAY | ||
d.dayOfWeek(); // DayOfWeek.SATURDAY | ||
d.dayOfWeek().value(); // 6 | ||
d.dayOfYear(); // 359 | ||
d.dayOfYear(); // 359 | ||
d.isLeapYear(); // true 2016 is a leap year | ||
d.plusYears(1).isLeapYear() // false | ||
d.isLeapYear(); // true - 2016 is a leap year | ||
d.plusYears(1).isLeapYear(); // false | ||
@@ -135,10 +140,10 @@ // get the epoch day where 0 is 1970-01-01 | ||
// get range of month | ||
d.lengthOfMonth() // 31 | ||
d.lengthOfMonth(); // 31 | ||
d.range(ChronoField.DAY_OF_MONTH); // ValueRange(1 - 31) | ||
// get range of year | ||
d.lengthOfYear() // 366 | ||
d.range(ChronoField.DAY_OF_YEAR); // ValueRange(1 - 366) | ||
d.lengthOfYear(); // 366 | ||
d.range(ChronoField.DAY_OF_YEAR); // ValueRange(1 - 366) | ||
// get other date based field like the aligned week of year | ||
// get other date-based field like the aligned week of year | ||
d.get(ChronoField.ALIGNED_WEEK_OF_YEAR); // 52 | ||
@@ -148,66 +153,62 @@ | ||
d.get(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH); // 3 | ||
``` | ||
### Get weeks of week based year, get year quarters and the day of quarter | ||
### Get week of week-based year, quarter of year, day of quarter | ||
```javascript | ||
// get week of week-based year as defined by ISO 8601, with a Monday-based week | ||
d.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR); // 51 | ||
// get week of week based year as defined by ISO 8601 with a monday based week | ||
d.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR); // 51 | ||
d.isoWeekOfWeekyear(); // 51, equivalent to the above | ||
d.isoWeekyear(); // 2016 | ||
d.isoWeekOfWeekyear(); // 51, is the same as above | ||
d.isoWeekyear(); // 2016 | ||
LocalDate.of(2017, 1, 1).isoWeekOfWeekyear(); // 52 | ||
LocalDate.of(2017, 1, 1).isoWeekyear(); // 2016 | ||
LocalDate.of(2017,1,1).isoWeekOfWeekyear(); // 52 | ||
LocalDate.of(2017,1,1).isoWeekyear(); // 2016 | ||
// set the date to week 52 of week-based year with the same day of week | ||
d.with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, 52); // 2016-12-31 | ||
// set the date to week 52 of week based year with the same day of week | ||
d.with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, 52); // 2016-12-31 | ||
// get the quarter of the year | ||
d.get(IsoFields.QUARTER_OF_YEAR); // 4 | ||
d.get(IsoFields.DAY_OF_QUARTER); // 85 | ||
d.get(IsoFields.QUARTER_OF_YEAR); // 4 | ||
d.get(IsoFields.DAY_OF_QUARTER); // 85 | ||
// set the date to 15th day of the third quarter | ||
d.with(IsoFields.QUARTER_OF_YEAR, 3).with(IsoFields.DAY_OF_QUARTER, 15) // 2016-07-15 | ||
// set the date to the 15th day of the third quarter | ||
d.with(IsoFields.QUARTER_OF_YEAR, 3).with(IsoFields.DAY_OF_QUARTER, 15); // 2016-07-15 | ||
``` | ||
### Adding to/ subtracting from a LocalDate | ||
### Adding to and subtracting from a `LocalDate` | ||
Note that each of these methods returns a new `LocalDate` instance. | ||
```javascript | ||
var d = LocalDate.parse('2016-02-23'); | ||
// add/ subtract 366 days | ||
// add/subtract 366 days | ||
d.plusDays(366); // '2017-02-23' | ||
d.minusDays(366); // '2015-02-22' | ||
// add/ subtract 12 months | ||
// add/subtract 12 months | ||
d.plusMonths(12); // '2017-02-23' | ||
d.minusMonths(12); // '2015-02-23' | ||
// add/ subtract 4 weeks | ||
// add/subtract 4 weeks | ||
d.plusWeeks(4); // '2016-03-22' | ||
d.minusWeeks(4); // '2016-01-26' | ||
// add/ subtract 1 year to the parsed LocalDate and returns a new instance | ||
// add/subtract 1 year | ||
d.plusYears(1); // '2017-02-23' | ||
d.minusYears(1); // '2015-02-23' | ||
// add/ subtract 30 years | ||
// add/subtract 30 years | ||
d.plus(3, ChronoUnit.DECADES); // '2046-02-23' | ||
d.minus(3, ChronoUnit.DECADES); // '1986-02-23' | ||
// add subtract a Period of 3 Months and 3 Days | ||
d.plus(Period.ofMonths(3).plusDays(3)) // '2016-05-26' | ||
d.minus(Period.ofMonths(3).plusDays(3)) // '2015-11-20' | ||
// add/subtract a Period of 3 Months and 3 Days | ||
d.plus(Period.ofMonths(3).plusDays(3)); // '2016-05-26' | ||
d.minus(Period.ofMonths(3).plusDays(3)); // '2015-11-20' | ||
``` | ||
### Alter certain fields of a LocalDate | ||
### Alter specific fields of a LocalDate | ||
```javascript | ||
var d = LocalDate.parse('2016-12-24'); | ||
@@ -228,3 +229,6 @@ | ||
// get the last day of the current month | ||
LocalDate.now().plusMonths(1).withDayOfMonth(1).minusDays(1); | ||
LocalDate.now() | ||
.plusMonths(1) | ||
.withDayOfMonth(1) | ||
.minusDays(1); | ||
@@ -234,30 +238,26 @@ // set the day of year | ||
// set the WEEK_OF_WEEK_BASED_YEAR to 52 | ||
d.with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, 52) // 2016-12-31 | ||
// set the week of week-based year to 52 | ||
d.with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, 52); // 2016-12-31 | ||
``` | ||
### Compare LocalDates | ||
### Compare one `LocalDate` with another | ||
```javascript | ||
var d1 = LocalDate.parse('2016-12-24'); | ||
var d2 = d1.plusDays(2); | ||
d1.isAfter(d2); // false | ||
d1.isAfter(d2); // false | ||
d1.isBefore(d2); // true | ||
d1.equals(d2); // false | ||
d1.equals(d1.plusDays(0)); // true | ||
d1.equals(d1.plusDays(1)); // false | ||
d1.equals(d2); // false | ||
d1.equals(d1.plusDays(0)); // true | ||
d1.equals(d1.plusDays(1)); // false | ||
d1.compareTo(d1) === 0; // true | ||
d1.compareTo(d2) < 0; // true | ||
d2.compareTo(d1) > 0; // true | ||
d1.compareTo(d2) < 0; // true | ||
d2.compareTo(d1) > 0; // true | ||
// Warn! hashCode is equal if in insances are equal, but might be equal for unequal instances as well | ||
d1.hashCode(); // 4129560 | ||
d2.hashCode(); // 4129562 | ||
d1.hashCode() !== d2.hashCode(); // true | ||
``` | ||
@@ -268,14 +268,12 @@ | ||
```javascript | ||
var d1 = LocalDate.parse('2016-12-24'); | ||
var d2 = d1.plusMonths(13).plusDays(42); | ||
// obtain the Period between the two dates | ||
d1.until(d2).toString(); // 'P1Y2M11D', output in ISO-8601 period format | ||
// obtain the Period between the two dates | ||
d1.until(d2).toString(); // 'P1Y2M11D' (1 year, 2 months, 11 days in ISO-8601 period format) | ||
d1.until(d2).toTotalMonths(); // 14 | ||
// obtain the distance between the two dates with a certain precision | ||
d1.until(d2, ChronoUnit.MONTHS); // 14, returns the distance in total months. | ||
d1.until(d2, ChronoUnit.DAYS); // 438, returns the distance in total days. | ||
// obtain the distance between the two dates with a specific precision | ||
d1.until(d2, ChronoUnit.MONTHS); // 14, returns the distance in total months | ||
d1.until(d2, ChronoUnit.DAYS); // 438, returns the distance in total days | ||
``` | ||
@@ -286,6 +284,6 @@ | ||
```javascript | ||
// obtain a LocalDate from a LocalDateTime instance | ||
LocalDate.from(LocalDateTime.now()); // current LocalDate e.g. 2016-02-25 | ||
LocalDateTime.now().toLocalDate(); // same | ||
var dt = LocalDateTime.now(); | ||
LocalDate.from(dt); // LocalDate from LocalDateTime | ||
dt.toLocalDate(); // LocalDateTime to LocalDate (equivalent to the above) | ||
@@ -300,11 +298,9 @@ var d1 = LocalDate.parse('2016-02-25'); | ||
// obtain a LocalDate from a JavaScript Date | ||
// the manual way | ||
var d = LocalDate.ofInstant(Instant.ofEpochMilli(new Date().getTime())); | ||
// the recommended way with the javascript temporal | ||
// the recommended way with the JavaScript temporal | ||
d = LocalDate.from(nativeJs(new Date())); | ||
// converting from a moment is workings the same way | ||
// converting from a moment works the same way | ||
d = LocalDate.from(nativeJs(moment())); | ||
``` | ||
@@ -314,21 +310,19 @@ | ||
TemporalAdjusters provide compact business logic for date based temporals such as LocalDate, LocalDateTime or ZonedDateTime. | ||
`TemporalAdjusters` provide compact business logic for date-based temporals such as `LocalDate`, `LocalDateTime` or `ZonedDateTime`. | ||
```javascript | ||
var d = LocalDate.parse('2016-12-24'); | ||
// get first/ last day of month | ||
d.with(TemporalAdjusters.firstDayOfMonth()) // 2016-12-01 | ||
d.with(TemporalAdjusters.lastDayOfMonth()) // 2016-12-31 | ||
d.with(TemporalAdjusters.firstDayOfMonth()); // 2016-12-01 | ||
d.with(TemporalAdjusters.lastDayOfMonth()); // 2016-12-31 | ||
// get the next specified weekday | ||
d.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY)) // 2016-12-25 | ||
d.with(TemporalAdjusters.nextOrSame(DayOfWeek.SATURDAY)) // 2016-12-24 | ||
d.with(TemporalAdjusters.next(DayOfWeek.SATURDAY)) // 2016-12-31 | ||
d.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY)); // 2016-12-25 | ||
d.with(TemporalAdjusters.nextOrSame(DayOfWeek.SATURDAY)); // 2016-12-24 | ||
d.with(TemporalAdjusters.next(DayOfWeek.SATURDAY)); // 2016-12-31 | ||
// get the first/last weekday of month | ||
d.with(TemporalAdjusters.lastInMonth(DayOfWeek.SATURDAY)) // 2016-12-31 | ||
d.with(TemporalAdjusters.firstInMonth(DayOfWeek.SATURDAY)) // 2016-12-03 | ||
d.with(TemporalAdjusters.lastInMonth(DayOfWeek.SATURDAY)); // 2016-12-31 | ||
d.with(TemporalAdjusters.firstInMonth(DayOfWeek.SATURDAY)); // 2016-12-03 | ||
``` | ||
@@ -340,90 +334,82 @@ | ||
A LocalTime represents a time without time-zone in the ISO-8601 calendar system such as '10:15:30' | ||
A `LocalTime` represents a time with **no date** and **no time zone** in the [ISO-8601](https://en.wikipedia.org/wiki/ISO_8601) calendar system, such as '10:15:30' | ||
### Create a LocalTime instance | ||
### Create a `LocalTime` instance | ||
```javascript | ||
// obtain the current time in the system default timezone, e.g. '10:29:05.743' | ||
// obtain the current time in the system default time zone, e.g. '10:29:05.743' | ||
LocalTime.now(); | ||
// obtain the current time in the utc timezone, e.g. '09:29:05.743' | ||
// obtain the current time in the UTC time zone, e.g. '09:29:05.743' | ||
LocalTime.now(ZoneOffset.UTC); | ||
// obtain an instance of LocalTime from an ISO8601 formatted text string | ||
LocalTime.parse('09:42'); // '09:42' | ||
LocalTime.parse('09:42:42'); // '09:42:42' | ||
// obtain an instance of LocalTime from an ISO 8601 formatted text string | ||
LocalTime.parse('09:42'); // '09:42' | ||
LocalTime.parse('09:42:42'); // '09:42:42' | ||
LocalTime.parse('09:42:42.123'); // '09:42:42.123' | ||
LocalTime.parse('09:42:42.123456789'); // '09:42:42.123456789' | ||
// obtain an instance of LocalTime from a hour, minute, second and nano value | ||
LocalTime.of(23, 55) // '23:55' | ||
LocalTime.of(23, 55, 42) // '23:55:42' | ||
LocalTime.of(23, 55, 42, 123000000) // '23:55:42.123' | ||
// obtain an instance of LocalTime from hour, minute, second, and nanosecond values | ||
LocalTime.of(23, 55); // '23:55' | ||
LocalTime.of(23, 55, 42); // '23:55:42' | ||
LocalTime.of(23, 55, 42, 123000000); // '23:55:42.123' | ||
// obtain an instance of LocalTime from second of day | ||
LocalTime.ofSecondOfDay(3666) // '01:01:06' | ||
// obtain an instance of LocalTime from second of day | ||
LocalTime.ofSecondOfDay(3666); // '01:01:06' | ||
``` | ||
### Get values from LocalTime | ||
### Get values from `LocalTime` | ||
```javascript | ||
var t = LocalTime.parse('23:55:42.123'); | ||
t.toString(); // '23:55:42.123' ISO8601 format | ||
t.toString(); // '23:55:42.123' ISO 8601 format | ||
t.hour(); // 23 | ||
t.hour(); // 23 | ||
t.minute(); // 55 | ||
t.second(); // 42 | ||
t.nano(); // 123000000 | ||
t.nano(); // 123000000 | ||
// get other time based fields | ||
t.get(ChronoField.SECOND_OF_DAY); // 86142 | ||
t.get(ChronoField.MILLI_OF_SECOND); // 123 | ||
t.get(ChronoField.HOUR_OF_AMPM); // 11 | ||
// any other time based ChronoField is allowed as param for get | ||
// get other time-based fields | ||
t.get(ChronoField.SECOND_OF_DAY); // 86142 | ||
t.get(ChronoField.MILLI_OF_SECOND); // 123 | ||
t.get(ChronoField.HOUR_OF_AMPM); // 11 | ||
// any other time-based ChronoField is allowed as param for get | ||
``` | ||
### Adding to/ subtracting from a LocalTime instance | ||
### Adding to/ subtracting from a `LocalTime` instance | ||
```javascript | ||
var t = LocalTime.parse('11:55:42'); | ||
var t = LocalTime.parse('11:55:42') | ||
// add/ subtract 12 hours | ||
// add/subtract 12 hours | ||
t.plusHours(12); // '23:55:42' | ||
t.minusHours(12); // '23:55:42' | ||
// add/ subtract 30 minutes | ||
// add/subtract 30 minutes | ||
t.plusMinutes(30); // '12:25:42' | ||
t.minusMinutes(30); // '11:25:42' | ||
// add/ subtract 30 seconds | ||
// add/subtract 30 seconds | ||
t.plusSeconds(30); // '11:56:12' | ||
t.minusSeconds(30); // '11:55:12' | ||
// add/ subtract 1.000.000 nanos (1 milli second) | ||
// add/subtract 1 million nanoseconds (1 millisecond) | ||
t.plusNanos(1000000); // '11:56:42.001' | ||
t.minusNanos(1000000); // '11:55:41.999' | ||
// add/ subtract a time based unit | ||
// add/subtract a time-based unit | ||
t.plus(1, ChronoUnit.MILLIS); // '11:55:42.001' | ||
t.plus(1, ChronoUnit.HALF_DAYS); // '23:55:42' | ||
// add/ subtract a duration of 15 minutes | ||
// add/subtract a duration of 15 minutes | ||
t.plus(Duration.ofMinutes(15)); // '12:10:42' | ||
t.minus(Duration.ofMinutes(15)); // '11:40:42' | ||
``` | ||
### Alter certain fields of a LocalTime instance | ||
### Alter specific fields of a `LocalTime` instance | ||
```javascript | ||
var t = LocalTime.parse('11:55:42'); | ||
var t = LocalTime.parse('11:55:42') | ||
// set the hour of day to 1 | ||
@@ -439,48 +425,46 @@ t.withHour(1); // '01:55:42' | ||
// set the MILLI_OF_SECOND to 51 | ||
t.with(ChronoField.MILLI_OF_SECOND, 51) // '11:55:42.051' | ||
t.with(ChronoField.MILLI_OF_SECOND, 51); // '11:55:42.051' | ||
// set by a custom TemporalAdjusters | ||
// sample of a custom adjuster that adjust to the next even second | ||
nextEvenSecond = { adjustInto: function(t){ return t.second() % 2 === 0 ? t.plusSeconds(2) : t.plusSeconds(1); } } | ||
t.with(nextEvenSecond) // '11:55:44' | ||
t.plusSeconds(1).with(nextEvenSecond) // '11:55:44' | ||
nextEvenSecond = { | ||
adjustInto: function(t) { | ||
return t.second() % 2 === 0 ? t.plusSeconds(2) : t.plusSeconds(1); | ||
}, | ||
}; | ||
t.with(nextEvenSecond); // '11:55:44' | ||
t.plusSeconds(1).with(nextEvenSecond); // '11:55:44' | ||
``` | ||
### Truncate a LocalTime instance | ||
### Truncate a `LocalTime` instance | ||
```javascript | ||
var t = LocalTime.parse('23:55:42.123'); | ||
var t = LocalTime.parse('23:55:42.123') | ||
t.truncatedTo(ChronoUnit.SECONDS); // '23:55:42' | ||
t.truncatedTo(ChronoUnit.MINUTES); // '23:55:00' | ||
t.truncatedTo(ChronoUnit.HOURS); // '23:00' | ||
t.truncatedTo(ChronoUnit.HOURS); // '23:00' | ||
t.truncatedTo(ChronoUnit.HALF_DAYS); // '12:00' | ||
t.truncatedTo(ChronoUnit.DAYS); // '00:00' | ||
t.truncatedTo(ChronoUnit.DAYS); // '00:00' | ||
``` | ||
### Compare LocalTime instances | ||
### Compare `LocalTime` instances | ||
```javascript | ||
var t1 = LocalTime.parse('11:55:42') | ||
var t1 = LocalTime.parse('11:55:42'); | ||
var t2 = t1.plusHours(2); | ||
t1.isAfter(t2); // false | ||
t1.isAfter(t2); // false | ||
t1.isBefore(t2); // true | ||
t1.equals(t1.plusHours(0)); // true | ||
t1.equals(t1.plusHours(1)); // false | ||
t1.equals(t1.plusHours(0)); // true | ||
t1.equals(t1.plusHours(1)); // false | ||
t1.compareTo(t1) === 0; // true | ||
t1.compareTo(t2) < 0; // true | ||
t2.compareTo(t1) > 0; // true | ||
t1.compareTo(t2) < 0; // true | ||
t2.compareTo(t1) > 0; // true | ||
// Warn! hashCode is equal if in insances are equal, but might be equal for unequal instances as well | ||
t1.hashCode(); // 916974646 | ||
t2.hashCode(); // -1743180648 | ||
t1.hashCode() !== t2.hashCode(); // true | ||
``` | ||
@@ -491,133 +475,125 @@ | ||
```javascript | ||
var t1 = LocalTime.parse('11:00'); | ||
var t2 = t1 | ||
.plusHours(2) | ||
.plusMinutes(42) | ||
.plusSeconds(12); | ||
var t1 = LocalTime.parse('11:00') | ||
var t2 = t1.plusHours(2).plusMinutes(42).plusSeconds(12); | ||
// obtain the duration between the two dates | ||
t1.until(t2, ChronoUnit.HOURS); // 2 | ||
t1.until(t2, ChronoUnit.MINUTES); // 162 | ||
t1.until(t2, ChronoUnit.SECONDS); // 9732 | ||
// obtain the duration between the two dates | ||
t1.until(t2, ChronoUnit.HOURS); // 2 | ||
t1.until(t2, ChronoUnit.MINUTES); // 162 | ||
t1.until(t2, ChronoUnit.SECONDS); // 9732 | ||
``` | ||
### Convert a LocalTime from a javascript Date or moment | ||
### Convert a `LocalTime` from a `moment` or JavaScript `Date` | ||
```javascript | ||
// obtain a LocalTime instance from a JavaScript Date | ||
// obtain a LocalTime instance from a JavaScript Date | ||
// the manual way | ||
var t = LocalTime.ofInstant(Instant.ofEpochMilli(new Date().getTime())); | ||
// the recommended way with the javascript temporal | ||
// the recommended way with the JavaScript temporal | ||
t = LocalTime.from(nativeJs(new Date())); | ||
// converting from a moment is workings the same way | ||
// converting from a `moment` instance works the same way | ||
d = LocalTime.from(nativeJs(moment())); | ||
``` | ||
## LocalDateTime | ||
A LocalDateTime represents a date-time without a time-zone in the ISO-8601 calendar system, such as '2007-12-03T10:15:30'. | ||
A LocalDateTime represents a date-time with **no time zone** in the [ISO-8601](https://en.wikipedia.org/wiki/ISO_8601) calendar system, such as '2007-12-03T10:15:30'. | ||
### Create a LocalDateTime instance | ||
### Create a `LocalDateTime` instance | ||
```javascript | ||
// obtain the current date and time in the system default timezone, e.g. '2016-02-26T10:29:05.743' | ||
// obtain the current date and time in the system default time zone, e.g. '2016-02-26T10:29:05.743' | ||
LocalDateTime.now(); | ||
// obtain the current date and time in the utc timezone | ||
// obtain the current date and time in the UTC time zone | ||
LocalDateTime.now(ZoneOffset.UTC); | ||
// obtain an instance of LocalDateTime from an ISO8601 formatted text string | ||
LocalDateTime.parse('2016-02-26T09:42'); // '2016-02-26T09:42' | ||
// obtain an instance of LocalDateTime from an ISO 8601 formatted text string | ||
LocalDateTime.parse('2016-02-26T09:42'); // '2016-02-26T09:42' | ||
LocalDateTime.parse('2016-02-26T09:42:42.123'); // '2016-02-26T09:42:42.123' | ||
// obtain an instance of LocalDateTime from a year, month, dayOfMonth, hour, minute, second and nano value | ||
LocalDateTime.of(2016,2,29); // "2016-02-29T00:00" | ||
LocalDateTime.of(2016,2,29,12,55,42); // "2016-02-29T12:55:42" | ||
LocalDateTime.of(2016,2,29,12,55,42,9) // "2016-02-29T12:55:42.000000009" | ||
// obtain an instance of LocalDateTime from year, month, dayOfMonth, hour, minute, second and nanosecond values | ||
LocalDateTime.of(2016, 2, 29); // '2016-02-29T00:00' | ||
LocalDateTime.of(2016, 2, 29, 12, 55, 42); // '2016-02-29T12:55:42' | ||
LocalDateTime.of(2016, 2, 29, 12, 55, 42, 9); // '2016-02-29T12:55:42.000000009' | ||
// obtain an instance of LocalDateTime from epoch seconds and a ZoneOffset | ||
LocalDateTime.ofEpochSecond(0, ZoneOffset.UTC) // "1970-01-01T00:00" | ||
LocalDateTime.ofInstant(Instant.now()) // current local date-time | ||
LocalDateTime.ofInstant(Instant.now(), ZoneOffset.UTC) // current local utc date-time | ||
LocalDateTime.ofEpochSecond(0, ZoneOffset.UTC); // '1970-01-01T00:00' | ||
LocalDateTime.ofInstant(Instant.now()); // current local date-time | ||
LocalDateTime.ofInstant(Instant.now(), ZoneOffset.UTC); // current local UTC date-time | ||
``` | ||
### Get values from LocalDateTime | ||
### Get values from `LocalDateTime` | ||
```javascript | ||
var dt = LocalDateTime.parse('2016-02-26T23:55:42.123'); | ||
dt.toString(); // '2016-02-26T23:55:42.123' ISO8601 format | ||
dt.toString(); // '2016-02-26T23:55:42.123' ISO 8601 format | ||
dt.year(); // 2016 | ||
dt.month(); // Month.FEBRUARY | ||
dt.monthValue(); // 2 | ||
dt.dayOfMonth(); // 26 | ||
dt.hour(); // 23 | ||
dt.year(); // 2016 | ||
dt.month(); // Month.FEBRUARY | ||
dt.monthValue(); // 2 | ||
dt.dayOfMonth(); // 26 | ||
dt.hour(); // 23 | ||
dt.minute(); // 55 | ||
dt.second(); // 42 | ||
dt.nano(); // 123000000 | ||
dt.nano(); // 123000000 | ||
dt.dayOfWeek(); // DayOfWeek.FRIDAY | ||
dt.dayOfWeek(); // DayOfWeek.FRIDAY | ||
dt.dayOfWeek().value(); // 5 | ||
dt.dayOfYear(); // 57 | ||
dt.dayOfYear(); // 57 | ||
dt.toLocalDate().isLeapYear(); // true 2016 is a leap year | ||
// obtain the LocalDate of the LocalDateTime | ||
dt.toLocalDate() | ||
// obtain the LocalTime of the LocalDateTime | ||
dt.toLocalTime() | ||
// obtain the date and time components of the LocalDateTime | ||
dt.toLocalDate(); | ||
dt.toLocalTime(); | ||
// get range of month | ||
dt.toLocalDate().lengthOfMonth() // 29 | ||
dt.toLocalDate().lengthOfMonth(); // 29 | ||
dt.range(ChronoField.DAY_OF_MONTH); // ValueRange(1 - 29) | ||
// get range of year | ||
dt.toLocalDate().lengthOfYear() // 366 | ||
dt.range(ChronoField.DAY_OF_YEAR); // ValueRange(1 - 366) | ||
dt.toLocalDate().lengthOfYear(); // 366 | ||
dt.range(ChronoField.DAY_OF_YEAR); // ValueRange(1 - 366) | ||
// get other date based field like the aligned week of year | ||
// get other date-based fields like the aligned week of year | ||
dt.get(ChronoField.ALIGNED_WEEK_OF_YEAR); // 9 | ||
// get week of week based year | ||
dt.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR); // 8 | ||
// get week of week-based year | ||
dt.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR); // 8 | ||
dt.toLocalDate().isoWeekOfWeekyear(); | ||
// get other time based fields | ||
dt.get(ChronoField.SECOND_OF_DAY); // 86142 | ||
dt.get(ChronoField.MILLI_OF_SECOND); // 123 | ||
dt.get(ChronoField.HOUR_OF_AMPM); // 11 | ||
// any other date or time based ChronoField is allowed as param for get | ||
// get other time-based fields | ||
dt.get(ChronoField.SECOND_OF_DAY); // 86142 | ||
dt.get(ChronoField.MILLI_OF_SECOND); // 123 | ||
dt.get(ChronoField.HOUR_OF_AMPM); // 11 | ||
// any other date or time-based ChronoField can be passed to `get` | ||
``` | ||
### Adding to/ subtracting from a LocalDateTime instance | ||
### Adding to and subtracting from a `LocalDateTime` instance | ||
```javascript | ||
var dt = LocalDateTime.parse('2016-02-26T23:55:42.123'); | ||
// add/ subtract 366 days | ||
// add/subtract 366 days | ||
dt.plusDays(366); // '2017-02-26T23:55:42.123' | ||
dt.minusDays(366); // '2015-02-25T23:55:42.123' | ||
// add/ subtract 12 months | ||
// add/subtract 12 months | ||
dt.plusMonths(12); // '2017-02-26' | ||
dt.minusMonths(12); // '2015-02-26' | ||
// add/ subtract 4 weeks | ||
// add/subtract 4 weeks | ||
dt.plusWeeks(4); // '2016-03-25T23:55:42.123' | ||
dt.minusWeeks(4); // '2016-01-29T23:55:42.123' | ||
// add/ subtract 1 year to the parsed LocalDate and returns a new instance | ||
// add/subtract 1 year to the parsed LocalDate and returns a new instance | ||
dt.plusYears(1); // '2017-02-26T23:55:42.123' | ||
dt.minusYears(1); // '2015-02-26T23:55:42.123' | ||
// add/ subtract 30 years | ||
// add/subtract 30 years | ||
dt.plus(3, ChronoUnit.DECADES); // '2046-02-26T23:55:42.123' | ||
@@ -627,35 +603,33 @@ dt.minus(3, ChronoUnit.DECADES); // '1986-02-26T23:55:42.123' | ||
// add subtract a Period of 3 Months and 3 Days | ||
dt.plus(Period.ofMonths(3).plusDays(3)) // '2016-05-29T23:55:42.123' | ||
dt.minus(Period.ofMonths(3).plusDays(3)) // '2015-11-23T23:55:42.123' | ||
dt.plus(Period.ofMonths(3).plusDays(3)); // '2016-05-29T23:55:42.123' | ||
dt.minus(Period.ofMonths(3).plusDays(3)); // '2015-11-23T23:55:42.123' | ||
// add/ subtract 12 hours | ||
// add/subtract 12 hours | ||
dt.plusHours(12); // '2016-02-27T11:55:42.123' | ||
dt.minusHours(12); // '2016-02-26T11:55:42.123' | ||
// add/ subtract 30 minutes | ||
// add/subtract 30 minutes | ||
dt.plusMinutes(30); // '2016-02-27T00:25:42.123' | ||
dt.minusMinutes(30); // '2016-02-26T23:25:42.123' | ||
// add/ subtract 30 seconds | ||
// add/subtract 30 seconds | ||
dt.plusSeconds(30); // '2016-02-26T23:56:12.123' | ||
dt.minusSeconds(30); // '2016-02-26T23:55:12.123' | ||
// add/ subtract 1.000.000 nanos (1 milli second) | ||
// add/subtract 1 million nanoseconds (1 millisecond) | ||
dt.plusNanos(1000000); // '2016-02-26T23:55:42.124' | ||
dt.minusNanos(1000000); // '2016-02-26T23:55:42.122' | ||
// add/ subtract a time based unit | ||
// add/subtract a time-based unit | ||
dt.plus(1, ChronoUnit.MILLIS); // '2016-02-26T23:55:42.124' | ||
dt.plus(1, ChronoUnit.HALF_DAYS); // '2016-02-26T11:55:42.123' | ||
// add/ subtract a duration of 30 hours and 45 minutes | ||
// add/subtract a duration of 30 hours and 45 minutes | ||
dt.plus(Duration.ofHours(30).plusMinutes(45)); // '2016-02-28T06:40:42.123' | ||
dt.minus(Duration.ofHours(30).plusMinutes(45)); // '2016-02-25T17:10:42.123' | ||
``` | ||
### Alter certain fields of a LocalDateTime instance | ||
### Alter specific fields of a `LocalDateTime` instance | ||
```javascript | ||
var dt = LocalDateTime.parse('2016-02-26T23:55:42.123'); | ||
@@ -672,20 +646,21 @@ | ||
// set the nano of second to 1 | ||
// set the nanosecond of second to 1 | ||
dt.withNano(0); // '2016-02-26T23:55:42' | ||
// set the MILLI_OF_SECOND to 51 | ||
dt.with(ChronoField.MILLI_OF_SECOND, 51) // '2016-02-26T23:55:42.051' | ||
// set the millisecond of second to 51 | ||
dt.with(ChronoField.MILLI_OF_SECOND, 51); // '2016-02-26T23:55:42.051' | ||
// set by a custom TemporalAdjusters | ||
// sample of a custom adjuster that adjust to the next even second | ||
var nextEvenSecond = { adjustInto: function(t){ return t.second() % 2 === 0 ? t.plusSeconds(2) : t.plusSeconds(1); } } | ||
dt.with(nextEvenSecond) // '2016-02-26T23:55:44.123' | ||
dt.plusSeconds(1).with(nextEvenSecond) // '2016-02-26T23:55:44.123' | ||
// set by a custom TemporalAdjuster that adjusts to the next even second | ||
var nextEvenSecond = { | ||
adjustInto: function(t) { | ||
return t.second() % 2 === 0 ? t.plusSeconds(2) : t.plusSeconds(1); | ||
}, | ||
}; | ||
dt.with(nextEvenSecond); // '2016-02-26T23:55:44.123' | ||
dt.plusSeconds(1).with(nextEvenSecond); // '2016-02-26T23:55:44.123' | ||
``` | ||
### Truncate a LocalDateTime instance | ||
### Truncate a `LocalDateTime` instance | ||
```javascript | ||
var dt = LocalDateTime.parse('2016-02-26T23:55:42.123'); | ||
@@ -695,24 +670,22 @@ | ||
dt.truncatedTo(ChronoUnit.MINUTES); // '2016-02-26T23:55:00' | ||
dt.truncatedTo(ChronoUnit.HOURS); // '2016-02-26T23:00' | ||
dt.truncatedTo(ChronoUnit.HOURS); // '2016-02-26T23:00' | ||
dt.truncatedTo(ChronoUnit.HALF_DAYS); // '2016-02-26T12:00' | ||
dt.truncatedTo(ChronoUnit.DAYS); // '2016-02-26T00:00' | ||
dt.truncatedTo(ChronoUnit.DAYS); // '2016-02-26T00:00' | ||
``` | ||
### Compare LocalDateTime instances | ||
### Compare `LocalDateTime` instances | ||
```javascript | ||
var dt1 = LocalDateTime.parse('2016-02-26T23:55:42.123'); | ||
var dt2 = dt1.plusHours(2); | ||
dt1.isAfter(dt2); // false | ||
dt1.isAfter(dt2); // false | ||
dt1.isBefore(dt2); // true | ||
dt1.equals(dt1.plusHours(0)); // true | ||
dt1.equals(dt1.plusHours(1)); // false | ||
dt1.equals(dt1.plusHours(0)); // true | ||
dt1.equals(dt1.plusHours(1)); // false | ||
dt1.compareTo(dt1) === 0; // true | ||
dt1.compareTo(dt2) < 0; // true | ||
dt2.compareTo(dt1) > 0; // true | ||
dt1.compareTo(dt2) < 0; // true | ||
dt2.compareTo(dt1) > 0; // true | ||
@@ -723,37 +696,38 @@ // Warn! hashCode is equal if in insances are equal, but might be equal for unequal instances as well | ||
dt1.hashCode() !== dt2.hashCode(); // true | ||
``` | ||
### Distance between local dates and times | ||
### Distance between two `LocalDateTime` instances | ||
```javascript | ||
var dt1 = LocalDateTime.parse('2016-02-26T23:55:42.123'); | ||
var dt2 = dt1.plusYears(6).plusMonths(12).plusHours(2).plusMinutes(42).plusSeconds(12); | ||
var dt2 = dt1 | ||
.plusYears(6) | ||
.plusMonths(12) | ||
.plusHours(2) | ||
.plusMinutes(42) | ||
.plusSeconds(12); | ||
// obtain the duration between the two dates | ||
dt1.until(dt2, ChronoUnit.YEARS); // 7 | ||
dt1.until(dt2, ChronoUnit.MONTHS); // 84 | ||
dt1.until(dt2, ChronoUnit.WEEKS); // 356 | ||
dt1.until(dt2, ChronoUnit.DAYS); // 2557 | ||
dt1.until(dt2, ChronoUnit.HOURS); // 61370 | ||
// obtain the duration between the two dates | ||
dt1.until(dt2, ChronoUnit.YEARS); // 7 | ||
dt1.until(dt2, ChronoUnit.MONTHS); // 84 | ||
dt1.until(dt2, ChronoUnit.WEEKS); // 356 | ||
dt1.until(dt2, ChronoUnit.DAYS); // 2557 | ||
dt1.until(dt2, ChronoUnit.HOURS); // 61370 | ||
dt1.until(dt2, ChronoUnit.MINUTES); // 3682242 | ||
dt1.until(dt2, ChronoUnit.SECONDS); // 220934532 | ||
``` | ||
### Convert from a javascript Date or moment | ||
### Convert from a `moment` or JavaScript `Date` | ||
```javascript | ||
// obtain a LocalDateTime instance from a JavaScript Date | ||
// obtain a LocalTime instance from a JavaScript Date | ||
// the manual way | ||
var t = LocalDateTime.ofInstant(Instant.ofEpochMilli(new Date().getTime())); | ||
// the recommended way with the javascript temporal | ||
var t = LocalDateTime.ofInstant( | ||
Instant.ofEpochMilli(new Date().getTime()) | ||
); | ||
// the recommended way with the JavaScript temporal | ||
t = LocalDateTime.from(nativeJs(new Date())); | ||
// converting from a moment is workings the same way | ||
// converting from a moment works the same way | ||
d = LocalDateTime.from(nativeJs(moment())); | ||
``` | ||
@@ -763,37 +737,40 @@ | ||
ZonedDateTime represents a date-time with a time-zone in the ISO-8601 calendar system. Without support for loading iana time-zone databases, | ||
ZonedDateTime currently only supports time-zones with a fixed Offset such as `UTC` or `UTC+02:00` and the system default time-zone `SYSTEM`. | ||
A `ZonedDateTime` represents a date-time with a [time offset](https://en.wikipedia.org/wiki/UTC_offset) and/or a [time zone](https://en.wikipedia.org/wiki/Time_zone) in the [ISO-8601](https://en.wikipedia.org/wiki/ISO_8601) calendar system. | ||
### The system default time zone | ||
On its own, `ZonedDateTime` only supports specifying **time offsets** such as `UTC` or `UTC+02:00`, plus the `SYSTEM` time zone ID. | ||
The `SYSTEM` time-zone is a NON standard zone-id, that is introduced by js-joda because the javascript spec does not provide an API | ||
for the system default zone-id. The javascript spec only provides the system default time-zone offset for a point in the timeline | ||
(Date.prototype.getTimezoneOffset()). | ||
### The `SYSTEM` zone ID | ||
It is not recommended to exchange zoned-date-times with the SYSTEM zone-id between javascript engines, | ||
because the default time-zone may differ on other machines. Before a ZonedDateTime is exchanged, | ||
it should be converted to a fixed offset zone. | ||
The `SYSTEM` zone ID is a non-standard ID that is specific to `js-joda`. It represents the default time zone of the current JavaScript runtime. The JavaScript spec does not provide an API this; it only provides the system default time offset for a point in the timeline (`Date.prototype.getTimezoneOffset()`). | ||
You should not exchange `ZonedDateTime` instances using the `SYSTEM` zone ID between JavaScript environments (e.g. between server and client, or between two servers). The time offset on another machine won't necessarily be the same as yours. Before sending a `ZonedDateTime` to someone else, convert it to a fixed offset: | ||
```javascript | ||
// get now with the default system time-zone | ||
// current time with default `SYSTEM` | ||
ZonedDateTime.now().toString(); // e.g. 2016-03-18T12:38:23.561+01:00[SYSTEM] | ||
// convert it to ZonedDateTime with a fixed offset | ||
ZonedDateTime.now().withFixedOffsetZone().toString(); // e.g. 2016-03-18T12:38:23.561+01:00 | ||
// converted to a fixed time offset | ||
ZonedDateTime.now() | ||
.withFixedOffsetZone() | ||
.toString(); // e.g. 2016-03-18T12:38:23.561+01:00 | ||
``` | ||
### Iana tzdb support | ||
### Working with time zones | ||
For iana tzdb support use the plugin [js-joda-timezone](https://github.com/js-joda/js-joda-timezone). | ||
See https://github.com/js-joda/js-joda-timezone for more information. | ||
The plugin gives support for zone regions like e.g. `Europe/Berlin` or `America/New_York`. | ||
A **time zone** and a **time offset** are [not the same thing](https://en.wikipedia.org/wiki/UTC_offset#Time_zones_and_time_offsets). Some timezones change from standard time to [daylight savings time](https://en.wikipedia.org/wiki/Daylight_saving_time) and back every year: | ||
- In the `Europe/Berlin` _time zone_, the _time offset_ is `UTC+2` during the summer, and `UTC+1` during the rest of the year. | ||
- In the `Africa/Lagos` _time zone_, on the other hand, the _time offset_ is `UTC+1` all year round. | ||
Calculations that might span time zones or daylight savings transitions need to reference the time zone, not just the offset. | ||
The [js-joda-timezone](https://github.com/js-joda/js-joda-timezone) package provides bindings to the the [IANA tz database](https://www.iana.org/time-zones), making `joda-js`'s calculations time zone aware. The `tz` database uses zone names like `Africa/Bujumbura`, `America/New_York`, and `Europe/Lisbon` (see the [full list](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones)). | ||
To specify time zones using these names, you just need to `require` [js-joda-timezone](https://github.com/js-joda/js-joda-timezone). | ||
```javascript | ||
var jsJoda = require('js-joda'); | ||
require('js-joda-timezone'); | ||
// example how to use the plugin in node | ||
jsJoda = require('js-joda') | ||
.use(require('js-joda-timezone')) | ||
var zdt = ZonedDateTime.now(ZoneId.of('Europe/Paris')); | ||
``` | ||
@@ -804,13 +781,12 @@ | ||
```javascript | ||
// get now with the default system time-zone | ||
// get now with the default system time zone | ||
ZonedDateTime.now().toString(); // e.g. 2016-03-18T12:38:23.561+01:00[SYSTEM] | ||
// get now with the UTC time-zone | ||
// get now with the UTC time zone | ||
ZonedDateTime.now(ZoneOffset.UTC).toString(); // e.g. 2016-03-18T11:38:23.561Z | ||
// get now with a fixed offset time-zone | ||
// get now with a fixed offset time zone | ||
ZonedDateTime.now(ZoneId.of('UTC-05:00')).toString(); // e.g. 2016-03-18T06:38:23.561-05:00[UTC-05:00] | ||
// get now with a ZoneRegion | ||
// get now with a ZoneRegion (requires `js-joda-timezone`) | ||
ZonedDateTime.now(ZoneId.of('Europe/Paris')).toString(); // e.g. 2017-02-04T17:01:15.846+01:00[Europe/Paris] | ||
@@ -825,47 +801,57 @@ | ||
// create from a LocalDate(Time) | ||
LocalDate.parse('2012-06-06').atStartOfDay().atZone(ZoneId.of('Europe/Paris')); // 2012-06-06T00:00+02:00[Europe/Paris] | ||
ZonedDateTime.of(LocalDateTime.parse('2012-06-06T00:00'), ZoneId.of('Europe/Paris')); // 2012-06-06T00:00+02:00[Europe/Paris] | ||
ZonedDateTime.of(LocalDate.parse('2012-06-06'), LocalTime.MIDNIGHT, ZoneId.of('Europe/Paris')) // 2012-06-06T00:00+02:00[Europe/Paris] | ||
// create from a LocalDate(Time) (requires `js-joda-timezone`) | ||
LocalDate.parse('2012-06-06') | ||
.atStartOfDay() | ||
.atZone(ZoneId.of('Europe/Paris')); // 2012-06-06T00:00+02:00[Europe/Paris] | ||
ZonedDateTime.of( | ||
LocalDateTime.parse('2012-06-06T00:00'), | ||
ZoneId.of('Europe/Paris') | ||
); // 2012-06-06T00:00+02:00[Europe/Paris] | ||
ZonedDateTime.of( | ||
LocalDate.parse('2012-06-06'), | ||
LocalTime.MIDNIGHT, | ||
ZoneId.of('Europe/Paris') | ||
); // 2012-06-06T00:00+02:00[Europe/Paris] | ||
// create by Instant | ||
ZonedDateTime.ofInstant(Instant.now(), ZoneId.SYSTEM) // current system time | ||
// create from an Instant | ||
ZonedDateTime.ofInstant(Instant.now(), ZoneId.SYSTEM); // current system time | ||
``` | ||
### Switch timezones | ||
### Switch time zones | ||
> These examples require `js-joda-timezone`. | ||
```javascript | ||
var d = LocalDate.of(2016, 3, 18); | ||
var zdt = d.atTime(LocalTime.NOON).atZone(ZoneId.of('America/New_York')); //2016-03-18T12:00-04:00[America/New_York] | ||
var d = LocalDate.of(2016, 3, 18) | ||
var zdt = d.atTime(LocalTime.NOON).atZone(ZoneId.of('America/New_York')) //2016-03-18T12:00-04:00[America/New_York] | ||
// switch timezone retaining the local date-time if possible | ||
// switch time zone retaining the local date-time if possible | ||
zdt.withZoneSameLocal(ZoneId.of('Europe/Berlin')); // 2016-03-18T12:00+01:00[Europe/Berlin] | ||
// switch timezone and retain the instant | ||
// switch time zone and retain the instant | ||
zdt.withZoneSameInstant(ZoneId.of('Europe/Berlin')); // 2016-03-18T17:00+01:00[Europe/Berlin] | ||
``` | ||
### Get and manipulate values from a `ZonedDateTime` | ||
``` | ||
`ZonedDateTime` implements the same methods as `LocalDateTime` for getting or setting values. See [the examples above](#get-values-from-localdatetime) for `LocalDateTime`. | ||
### Get and manipulate values from a ZonedDateTime | ||
### Calculate values across daylight savings transitions | ||
Check the examples for LocalDate and LocalDateTime. ZonedDateTime implements the same methods as LocalDateTime | ||
for getting or setting values. | ||
When adding to or subtracting from a `ZonedDateTime` instance, the calculation is different depending on whether date or time units are passed. | ||
The calculation for date and time units differ. Date units operate on the local time-line. Time units operate on the instant time-line. | ||
The following example shows the difference for a daylight saving transition. | ||
- Addition/subtraction of **date units** are made on the **local** timeline. | ||
- Addition/subtraction of **time units** are made on the **instant** timeline. | ||
This example shows the difference for a daylight saving transition. | ||
```javascript | ||
// assume the system default time zone is CET; we define a time as 2016-03-18 at 17:00 local time | ||
var zdt = ZonedDateTime.parse('2016-03-18T17:00+01:00[Europe/Berlin]'); | ||
// assume the system default time zone is CET and its 2016-03-18 at noon local time. | ||
var zdt = ZonedDateTime.parse('2016-03-18T12:00+01:00[Europe/Berlin]'); | ||
// adding a date unit of 2 weeks, crossing a daylight saving transition | ||
zdt.plusWeeks(2); // 2016-04-01T17:00+02:00[Europe/Berlin] (still 17:00) | ||
// adding a date unit of 2 weeks (crossing a daylight saving transition) | ||
zdt.plusWeeks(2); // still noon: 2016-04-01T12:00+02:00[Europe/Berlin] | ||
// adding a time unit of 2 weeks (2 * 7 * 24) | ||
zdt.plusHours(2 * 7 * 24); // 1 pm: 2016-04-01T13:00+02:00[Europe/Berlin] | ||
zdt.plusHours(2 * 7 * 24); // 2016-04-01T18:00+02:00[Europe/Berlin] (now 18:00) | ||
``` | ||
@@ -875,23 +861,29 @@ | ||
Period is a date-based amount of time in the ISO-8601 calendar system, such as '2 years, 3 months and 4 days'. | ||
`Period` is a **date-based** amount of time in the ISO-8601 calendar system, such as '2 years, 3 months and 4 days'. | ||
```javascript | ||
// parse and format ISO8601 period strings | ||
// parse and format ISO 8601 period strings | ||
Period.parse('P1Y10M').toString(); // 'P1Y10M' | ||
// obtain a Period of 10 years, 5 month and 30 days | ||
Period.of(10, 5, 30).toString(); // "P10Y5M30D" | ||
Period.of(10, 5, 30).toString(); // 'P10Y5M30D' | ||
// 10 years | ||
Period.ofYears(10).toString(); // "P10Y" | ||
Period.ofYears(10).toString(); // 'P10Y' | ||
// add 45 days to a Period | ||
Period.ofYears(10).plusDays(45).toString(); // "P10Y45D" | ||
Period.ofYears(10) | ||
.plusDays(45) | ||
.toString(); // 'P10Y45D' | ||
// normalize a Period of years and month | ||
Period.of(1, 37, 0).normalized().toString(); // "P4Y1M" | ||
Period.of(1, 37, 0) | ||
.normalized() | ||
.toString(); // 'P4Y1M' | ||
// add/ subtract from a Period | ||
Period.ofYears(10).plusMonths(10).minusDays(42).toString(); // "P10Y10M-42D" | ||
// add/subtract from a Period | ||
Period.ofYears(10) | ||
.plusMonths(10) | ||
.minusDays(42) | ||
.toString(); // 'P10Y10M-42D' | ||
@@ -905,4 +897,6 @@ // add a Period to LocalDate | ||
// calculate the Period between two Dates | ||
Period.between(LocalDate.parse('2012-06-30'), LocalDate.parse('2012-08-31')); // "P2M1D" | ||
Period.between( | ||
LocalDate.parse('2012-06-30'), | ||
LocalDate.parse('2012-08-31') | ||
); // 'P2M1D' | ||
``` | ||
@@ -912,42 +906,39 @@ | ||
Duration is a time-based amount of time, such as '34.5 seconds'. | ||
`Duration` is a **time-based** amount of time, such as '34.5 seconds'. | ||
```javascript | ||
// obtain a Duration of 10 hours | ||
Duration.ofHours(10).toString(); // "PT10H" | ||
Duration.ofHours(10).toString(); // 'PT10H' | ||
// obtain a Duration of 10 days (10 x 24 hours) | ||
Duration.ofDays(10).toString(); // "PT240H" | ||
Duration.ofDays(10).toString(); // 'PT240H' | ||
// add/ subtract a duration from a LocalDateTime | ||
// add/subtract a duration from a LocalDateTime | ||
var dt = LocalDateTime.parse('2012-12-24T12:00'); | ||
dt.plus(Duration.ofHours(10).plusMinutes(30)).toString(); // '2012-12-24T22:30' | ||
dt.minus(Duration.ofHours(12).multipliedBy(10)).toString() // '2012-12-19T12:00' | ||
dt.minus(Duration.ofHours(12).multipliedBy(10)).toString(); // '2012-12-19T12:00' | ||
// calculate the durations beetween to time based temporals | ||
// calculate the durations beetween to time-based temporals | ||
var dt1 = LocalDateTime.parse('2012-12-24T12:00'); | ||
Duration.between(dt1, dt1.plusHours(10)).toString(); // "PT10H" | ||
Duration.between(dt1, dt1.plusHours(10)).toString(); // 'PT10H' | ||
``` | ||
## Customizing js-joda | ||
## Customize js-joda | ||
This package is extensible, allowing you to create your own custom temporal calculations. See the [temporal interface documentation](https://js-joda.github.io/js-joda/esdoc/class/src/temporal/Temporal.js~Temporal.html) for more information. | ||
js-joda is easily extendable, it allows you to create your own custom domain models or formatter. Check the temporal interface documentation | ||
in the temporal directory for more information. | ||
### Custom temporal adjuster | ||
```javascript | ||
// implement a TemporalAdjuster that the next or same even day of month | ||
var nextOrSameEvenDay = { | ||
adjustInto: function(t) { | ||
return t.dayOfMonth() % 2 === 0 ? t : t.plusDays(1); | ||
}, | ||
}; | ||
// implement a temporal/TemporalAdjuster that the next or same even day of month | ||
var nextOrSameEvenDay = { adjustInto: function(t){ return t.dayOfMonth() % 2 === 0 ? t : t.plusDays(1); } } | ||
LocalDateTime.parse('2012-12-23T12:00').with(nextOrSameEvenDay); // '2012-12-24T12:00' | ||
LocalDate.parse('2012-12-24').with(nextOrSameEvenDay); // '2012-12-24' | ||
``` | ||
@@ -957,28 +948,29 @@ | ||
A good starting point is temporal/IsoFields as an example how to implement custom fields and units. | ||
IsoFields implements fields and units for an ISO week based year. | ||
See the source for [temporal/IsoFields](https://github.com/js-joda/js-joda/blob/master/src/temporal/IsoFields.js) as an example how to implement custom fields and units. `IsoFields` implements fields and units for an ISO week-based year. | ||
### Custom formatter and queries | ||
The following example implements a date-time parser that parses a local date with an optional local time. | ||
the temporal query returns either a LocalDate or a LocalDateTime, depending on the parsed fields. | ||
The following example implements a parser for a local date with an optional local time. It returns either a `LocalDate` or a `LocalDateTime`, depending on the parsed fields. | ||
```javascript | ||
// build a custom date time formatter where the time field is optional | ||
var OPTIONAL_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd['T'HH:mm[:ss]]") | ||
var OPTIONAL_FORMATTER = DateTimeFormatter.ofPattern( | ||
'yyyy-MM-dd['T'HH:mm[:ss]]' | ||
); | ||
// create a temporal query that create a new Temporal depending on the existing fields | ||
dateOrDateTimeQuery = { | ||
queryFrom: function(temporal){ | ||
var date = temporal.query(TemporalQueries.localDate()); | ||
var time = temporal.query(TemporalQueries.localTime()); | ||
if(time==null) return date; | ||
else return date.atTime(time) | ||
} | ||
} | ||
queryFrom: function(temporal) { | ||
var date = temporal.query(TemporalQueries.localDate()); | ||
var time = temporal.query(TemporalQueries.localTime()); | ||
if (time == null) return date; | ||
else return date.atTime(time); | ||
} | ||
}; | ||
localDate = OPTIONAL_FORMATTER.parse('2012-12-24', dateOrDateTimeQuery); | ||
localDateTime = OPTIONAL_FORMATTER.parse('2012-12-24T23:59', dateOrDateTimeQuery); | ||
localDateTime = OPTIONAL_FORMATTER.parse( | ||
'2012-12-24T23:59', | ||
dateOrDateTimeQuery | ||
); | ||
``` |
@@ -297,3 +297,3 @@ declare namespace JSJoda { | ||
withLocale(): DateTimeFormatter | ||
withLocale(locale: Locale): DateTimeFormatter | ||
@@ -1238,2 +1238,4 @@ withResolverStyle(resolverStyle: ResolverStyle): DateTimeFormatter | ||
id(): string | ||
normalized(): ZoneId | ||
@@ -1341,3 +1343,3 @@ | ||
static ofLocal(localDateTime: LocalDateTime, zone: ZoneId, preferredOffset: ZoneOffset): ZonedDateTime | ||
static ofLocal(localDateTime: LocalDateTime, zone: ZoneId, preferredOffset: ZoneOffset | null): ZonedDateTime | ||
@@ -1344,0 +1346,0 @@ static ofStrict(localDateTime: LocalDateTime, offset: ZoneOffset, zone: ZoneId): ZonedDateTime |
@@ -186,3 +186,3 @@ /** | ||
withChronology(chrono: any): any; | ||
withLocale(): DateTimeFormatter; | ||
withLocale(locale: Locale): DateTimeFormatter; | ||
withResolverStyle(resolverStyle: ResolverStyle): DateTimeFormatter | ||
@@ -781,2 +781,3 @@ } | ||
hashCode(): number; | ||
id(): string; | ||
normalized(): ZoneId; | ||
@@ -783,0 +784,0 @@ rules(): ZoneRules; |
{ | ||
"name": "js-joda", | ||
"version": "1.9.2", | ||
"version": "1.9.3", | ||
"description": "a date and time library for javascript", | ||
@@ -27,3 +27,3 @@ "repository": { | ||
"test-ci": "npm run build-dist && npm run build-esdoc && npm run test && npm run test-browser -- --browsers \"Firefox,PhantomJS\" && npm run test-ts-definitions && npm run build-esdoc && npm run test-coverage", | ||
"test-ts-definitions": "tsc --noImplicitAny --noEmit --pretty --lib ES6 test/typescript_defintions/js-joda-tests.ts", | ||
"test-ts-definitions": "tsc --noImplicitAny --strict --noEmit --pretty --lib ES6 test/typescript_definitions/js-joda-tests.ts", | ||
"build-esdoc": "./node_modules/.bin/esdoc -c esdoc.json", | ||
@@ -52,9 +52,9 @@ "build-dist": "npx rollup -c rollup.config.js", | ||
"babel-preset-env": "^1.6.1", | ||
"chai": "^4.1.2", | ||
"coveralls": "^3.0.1", | ||
"chai": "^4.2.0", | ||
"coveralls": "^3.0.2", | ||
"esdoc": "^1.1.0", | ||
"esdoc-standard-plugin": "^1.0.0", | ||
"eslint": "^5.0.0", | ||
"eslint": "^5.7.0", | ||
"eslint-config-js-joda": "^1.0.0", | ||
"karma": "^2.0.3", | ||
"karma": "^3.0.0", | ||
"karma-chai-plugins": "^0.9.0", | ||
@@ -67,6 +67,6 @@ "karma-chrome-launcher": "^2.2.0", | ||
"karma-sourcemap-loader": "^0.3.7", | ||
"karma-webpack": "^3.0.0", | ||
"karma-webpack": "^3.0.5", | ||
"markdown-toc": "^1.2.0", | ||
"mocha": "^5.2.0", | ||
"nyc": "^12.0.2", | ||
"nyc": "^13.0.1", | ||
"phantomjs-prebuilt": "^2.1.16", | ||
@@ -76,4 +76,4 @@ "rollup": "^0.62.0", | ||
"rollup-plugin-uglify": "^4.0.0", | ||
"typescript": "^2.9.2", | ||
"webpack": "^4.12.0" | ||
"typescript": "^3.1.3", | ||
"webpack": "^4.20.2" | ||
}, | ||
@@ -80,0 +80,0 @@ "license": "BSD-3-Clause", |
147
README.md
@@ -1,10 +0,8 @@ | ||
Immutable date and time library for javascript | ||
============================================== | ||
# Immutable date and time library for JavaScript | ||
[![npm version](https://badge.fury.io/js/js-joda.svg)](https://badge.fury.io/js/js-joda) | ||
[![Build Status](https://travis-ci.org/js-joda/js-joda.svg?branch=master)](https://travis-ci.org/js-joda/js-joda) | ||
[![Build Status](https://travis-ci.org/js-joda/js-joda.svg)](https://travis-ci.org/js-joda/js-joda) | ||
[![Sauce Test Status](https://saucelabs.com/buildstatus/js-joda)](https://saucelabs.com/u/js-joda) | ||
[![Coverage Status](https://coveralls.io/repos/js-joda/js-joda/badge.svg?branch=master&service=github)](https://coveralls.io/github/js-joda/js-joda?branch=master) | ||
[![Tested node version](https://img.shields.io/badge/tested_with-current_node_LTS-blue.svg?style=flat)]() | ||
[![Downloads/Month](https://img.shields.io/npm/dm/js-joda.svg)](https://img.shields.io/npm/dm/js-joda.svg) | ||
@@ -15,28 +13,22 @@ [![Sauce Test Status](https://saucelabs.com/browser-matrix/js-joda.svg)](https://saucelabs.com/u/js-joda) | ||
+ **js-joda** is an **immutable date and time library** for javascript. It provides a **simple, domain-driven and clean API** based on the **ISO8601** calendar. | ||
**js-joda** is an **immutable date and time library** for JavaScript. It provides a **simple, domain-driven and clean API** based on the **ISO8601** calendar. | ||
+ js-joda has a lightweight footprint, only **46 kB minified and compressed**, no third party dependencies. | ||
+ js-joda is **fast**. It is about 2 to 10 times faster than other javascript date libraries. | ||
+ js-joda supports **ECMAScript 5** browsers down to ie9. | ||
- js-joda has a lightweight footprint, only **43 kB minified and compressed**, no third party dependencies. | ||
+ js-joda is a **port of the threeten** backport, that is the base for JSR-310 implementation of the Java SE 8 java.time package. Threeten is inspired by **Joda-Time**, having similar concepts and the same author. | ||
- js-joda is **fast**. It is about 2 to 10 times faster than other JavaScript date libraries. | ||
+ js-joda is **robust and stable**. We ported more then 1700 test-cases with a lots of test-permutations from the threetenbp project. We run the automated karma test-suite against Firefox, Chrome, Node and phantomjs. | ||
- js-joda supports **ECMAScript 5** browsers down to ie9. | ||
## Why yet another javascript date and time library | ||
- js-joda is a **port of the threeten** backport, which is the base for JSR-310 implementation of the Java SE 8 java.time package. Threeten is inspired by **Joda-Time**, having similar concepts and the same author. | ||
+ Popular javascript date libraries like moment or date-utils are wrappers around the native javascript Date object, | ||
providing syntactic sugar. The native Date object always consist of a date, time and a timezone part. | ||
In opposite to that, js-joda is a standalone date and time implementation. | ||
- js-joda is **robust and stable**. We ported more then 1700 test-cases with a lots of test-permutations from the threetenbp project. We run the automated karma test-suite against Firefox, Chrome, Node and phantomjs. | ||
+ The API has a domain-driven design with classes for the different use cases, like LocalDate, ZonedDateTime or Period. | ||
For examples LocalDate allows to handle dates like birthdays or holidays in a clean and error-safe way, | ||
especially if these dates are persisted to an external server. | ||
## Why yet another JavaScript date and time library? | ||
+ js-joda is immutable. Immutability aligns well with pure functions and | ||
with the architecture of frameworks like React and Flux. | ||
- Popular JavaScript date libraries like [moment](https://momentjs.com/) or [date-utils](https://github.com/continuouscalendar/dateutils) are **wrappers** around the native JavaScript `Date` object, providing syntactic sugar. The native `Date` object always consist of a date, time and a timezone part. In contrast, js-joda is a **standalone** date and time implementation. | ||
- The API has a **domain-driven design** with classes for each of the different use cases, like `LocalDate`, `ZonedDateTime` or `Period`. For example, `LocalDate` allows you to handle dates without times (like birthdays or holidays) in a clean and error-safe way, especially if these dates are persisted to an external server. | ||
- js-joda is **immutable**. Immutability aligns well with pure functions and with the architecture of frameworks like React and Flux. | ||
## The threeten domain models | ||
@@ -46,29 +38,29 @@ | ||
+ **LocalDate** represents a date without a time and time-zone in the ISO-8601 calendar system, such as 2007-12-24. | ||
- **LocalDate** represents a date without a time and time-zone in the ISO-8601 calendar system, such as 2007-12-24. | ||
+ **LocalTime** represents a time without time-zone in the ISO-8601 calendar system such as '11:55:00'. | ||
- **LocalTime** represents a time without time-zone in the ISO-8601 calendar system such as '11:55:00'. | ||
+ **LocalDateTime** is a description of the date (LocalDate), as used for birthdays, combined with the local time (LocalTime) as seen on a wall clock. | ||
- **LocalDateTime** is a description of the date (LocalDate), as used for birthdays, combined with the local time (LocalTime) as seen on a wall clock. | ||
+ **ZonedDateTime** is a date-time with a time-zone in the ISO-8601 calendar system, such as 2007-12-24T16:15:30+01:00 UTC+01:00. | ||
- **ZonedDateTime** is a date-time with a time-zone in the ISO-8601 calendar system, such as 2007-12-24T16:15:30+01:00 UTC+01:00. | ||
+ **Instant** is an instantaneous point on the time-line measured from the epoch of *1970-01-01T00:00:00Z* in epoch-seconds and nanosecond-of-second. | ||
- **Instant** is an instantaneous point on the time-line measured from the epoch of _1970-01-01T00:00:00Z_ in epoch-seconds and nanosecond-of-second. | ||
### Duration and Period | ||
+ **Duration** is a time-based amount of time, such as '34.5 seconds'. | ||
- **Duration** is a time-based amount of time, such as '34.5 seconds'. | ||
+ **Period** is a date-based amount of time in the ISO-8601 calendar system, such as '2 years, 3 months and 4 days'. | ||
- **Period** is a date-based amount of time in the ISO-8601 calendar system, such as '2 years, 3 months and 4 days'. | ||
### Additional value types | ||
+ **Year** represents a year in the ISO-8601 calendar system, such as '2016'. | ||
- **Year** represents a year in the ISO-8601 calendar system, such as '2016'. | ||
+ **YearMonth** represents a year and a month in the ISO-8601 calendar system, such as '2016-01'. | ||
- **YearMonth** represents a year and a month in the ISO-8601 calendar system, such as '2016-01'. | ||
+ **Month** represents a month-of-year in the ISO-8601 calendar system, such as 'July'. | ||
- **Month** represents a month-of-year in the ISO-8601 calendar system, such as 'July'. | ||
+ **MonthDay** represents a month-day in the ISO-8601 calendar system, such as '--12-03'. Could be used to represent e.g. Birthdays. | ||
- **MonthDay** represents a month-day in the ISO-8601 calendar system, such as '--12-03'. Could be used to represent e.g. Birthdays. | ||
+ **DayOfWeek** represents a day-of-week in the ISO-8601 calendar system, such as 'Tuesday'. | ||
- **DayOfWeek** represents a day-of-week in the ISO-8601 calendar system, such as 'Tuesday'. | ||
@@ -80,17 +72,15 @@ ## Getting started | ||
Install joda using npm | ||
```bash | ||
npm install js-joda | ||
``` | ||
Then require it to any module | ||
```javascript | ||
var LocalDate = require('js-joda').LocalDate; | ||
var d = LocalDate.parse('2012-12-24').atStartOfDay().plusMonths(2); // 2013-02-24T00:00:00 | ||
``` | ||
### Browser | ||
To use js-joda from a browser, download either dist/js-joda.min.js or dist/js-joda.js (with sourcemaps for development) | ||
To use js-joda from a browser, download either `dist/js-joda.min.js` or `dist/js-joda.js` (with sourcemaps for development). Then add it as a script tag to your page | ||
Then add it as a script tag to your page | ||
```html | ||
<script src="js-joda.min.js"></script> | ||
@@ -101,75 +91,60 @@ <script> | ||
</script> | ||
``` | ||
## Documentation | ||
+ [Cheat Sheet](CheatSheet.md) Quick start guide | ||
+ [API](//js-joda.github.io/js-joda/esdoc/) ESDoc generated API documentation | ||
+ [js-joda Homepage](http://js-joda.github.io/js-joda/) Project homepage | ||
- [js-joda Quick start guide](//js-joda.github.io/js-joda/manual/getting-started.html) Quick start guide and examples | ||
- [API](//js-joda.github.io/js-joda/identifiers.html) ESDoc generated API documentation | ||
## Roadmap | ||
### Milestone 1 core domains (reached with version v1.0.0) | ||
### Milestone 1: Core domains (reached with version v1.0.0) | ||
Support for the domain models LocalDate, LocalDateTime, ZonedDateTime, Instant, Duration | ||
and Period converting from and to ISO8601. ZonedDateTime (without support for loading iana time-zone databases) currently supports | ||
only fixed offsets like UTC or UTC+02:00 and the system default time zone. | ||
### Milestone 2 iana timezone support (reached with version v1.2.0) | ||
- Support for the domain models `LocalDate`, `LocalDateTime`, `ZonedDateTime`, `Instant`, `Duration` and `Period` converting to and from ISO8601. | ||
- `ZonedDateTime` (without support for loading iana time-zone databases) currently supports only fixed offsets like UTC or UTC+02:00 and the system default time zone. | ||
Add iana timezone database support to js-joda. Implement handling of Daylight saving transitions mainly in ZonedDateTime. | ||
### Milestone 2: IANA timezone support (reached with version v1.2.0) | ||
For having access to the iana timezone database, the plugin [js-joda-timezone](https://github.com/js-joda/js-joda-timezone) is required. It is providing an implementation of the [ZoneRulesProvider](https://js-joda.github.io/js-joda/esdoc/class/src/zone/ZoneRulesProvider.js~ZoneRulesProvider.html) and contains the iana timezone database. | ||
- Add IANA timezone database support to js-joda. Implement handling of daylight saving transitions, mainly in `ZonedDateTime`. | ||
- For access to the IANA timezone database, the plugin [js-joda-timezone](//github.com/js-joda/js-joda-timezone) is required. It provides an implementation of the [ZoneRulesProvider](//js-joda.github.io/js-joda/esdoc/class/src/zone/ZoneRulesProvider.js~ZoneRulesProvider.html) and contains the iana timezone database. | ||
### Milestone 3 locale support | ||
### Milestone 3: Locale support (reached with v2.0.0 of js-joda-locale) | ||
Add locale support. | ||
- Add locale support. | ||
- Extend pattern parser/ formatter for text with locale support. | ||
Extend pattern parser/ formatter for text with locale support. | ||
see the plugin [js-joda-locale](//github.com/js-joda/js-joda-locale) | ||
### Future Milestones | ||
* Reduce library size be removing redundant code, especially by refactoring code for formatting/ parsing dates. | ||
* Increase test coverage (ongoing task) | ||
* Cleanup documentation (ongoing task) | ||
* Improve static factory API design and make it more javascript style. | ||
One idea is to remove static factory methods like parse, from, of and unify it to one factory methods per domain. | ||
E.g. localDate(isoDate: string), localDate(year: number, month: number, dayOfMonth: number) | ||
* Merge methods get and getLong, differ between int and long values make no sense with javascript | ||
* Simplify temporal adjusters (amount, etc) by using functions instead of classes or objects | ||
* Replace API getters by [native getters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get), | ||
like replace `localDate.year()` by `localDate.year` | ||
* ... | ||
- Reduce library size by removing redundant code, especially by refactoring code for formatting/ parsing dates. | ||
- Increase test coverage (ongoing task) | ||
- Cleanup documentation (ongoing task) | ||
- Improve static factory API design and make it more JavaScript style. One idea is to remove static factory methods like parse, from, of and unify it to one factory method per domain. E.g. localDate(isoDate: string), localDate(year: number, month: number, dayOfMonth: number) | ||
- Merge methods get and getLong (difference between `int` and `long` values makes no sense with JavaScript) | ||
- Simplify temporal adjusters (amount, etc) by using functions instead of classes or objects | ||
## Contributing | ||
Contributions are always welcome. Before contributing please read the [code of conduct](http://contributor-covenant.org/version/1/4/) & | ||
search the issue tracker. We use GitHub issues. Your issue may have already been discussed or fixed. | ||
To contribute, fork js-joda, commit your changes, & send a pull request. | ||
Contributions are always welcome. Before contributing please read the [code of conduct](http://contributor-covenant.org/version/1/4/) & | ||
search the issue tracker. We use GitHub issues. Your issue may have already been discussed or fixed. To contribute, fork js-joda, commit your changes, & send a pull request. | ||
By contributing to js-joda, you agree that your contributions will be licensed under its BSD license. | ||
Note that pull requests and issues will only be considered so far as matching the threeten backport API. | ||
Additional requested features will be rejected. | ||
Note that only pull requests and issues that match the threeten backport API will be considered. Additional requested features will be rejected. | ||
## License | ||
Joda time is the base for JSR-310 that became part of Java SE 8 in the java.time package. | ||
JSR-310 is a new implementation with an API 'inspired by Joda-Time' but improvements on some design flaws (see | ||
http://blog.joda.org/2009/11/why-jsr-310-isn-joda-time_4941.html) | ||
- `Joda-Time` is the base for JSR-310 that became part of Java SE 8 in the java.time package. JSR-310 is a new implementation with an API 'inspired by Joda-Time' but improves on some design flaws (see http://blog.joda.org/2009/11/why-jsr-310-isn-joda-time_4941.html) `Joda-Time` is under Apache 2.0 licence. | ||
js-joda is using the ThreeTen-Backport implementation (http://www.threeten.org/threetenbp/) as a reference base for implementation. | ||
This allows us to release js-joda under the BSD License while the OpenJDK java.time implementation is under GNU GPL+linking exception. | ||
The API of the ThreeTen-Backport is mostly identical to the official Java SE 8 API from the view of our javascript port. | ||
`js-joda` uses the ThreeTen-Backport implementation (http://www.threeten.org/threetenbp/) as a reference base for implementation. This allows us to release js-joda under the BSD License while the OpenJDK java.time implementation is under GNU GPL+linking exception. The API of the ThreeTen-Backport is mostly identical to the official Java SE 8 API from the view of our JavaScript port. | ||
+ js-joda is released under the [BSD 3-clause license](LICENSE): | ||
- `js-joda` is released under the [BSD 3-clause license](//github.com/js-joda/js-joda/blob/master/LICENSE). | ||
+ our implementation reference base ThreeTen-Backport (http://www.threeten.org/threetenbp/) is also released under the BSD 3-clause license | ||
- Our implementation reference base ThreeTen-Backport (http://www.threeten.org/threetenbp/) is also released under the BSD 3-clause license | ||
+ Joda-Time is under Apache 2.0 licence. | ||
- `OpenJDK` is under GNU GPL+linking exception. | ||
+ OpenJDK is under GNU GPL+linking exception. | ||
- The author of `Joda-Time` and the lead architect of the JSR-310 is Stephen Colebourne. | ||
+ The author of joda time and the lead architect of the JSR-310 is Stephen Colebourne. | ||
The API of this project (as far as possible with javascript), a lot of implementation details and documentation | ||
The API of this project (as far as possible with JavaScript), a lot of implementation details and documentation | ||
are just copied but never equalled. |
@@ -557,3 +557,3 @@ /** | ||
* @param {!(Duration|number)} durationOrNumber | ||
* @param {!TemporaloUnit|number} unitOrNumber | ||
* @param {!TemporalUnit|number} unitOrNumber | ||
* @returns {Duration} | ||
@@ -1130,3 +1130,3 @@ */ | ||
* the relevant hours, minutes or seconds part of the duration. | ||
* Any fractional seconds are placed after a decimal povar i the seconds section. | ||
* Any fractional seconds are placed after a decimal point in the seconds section. | ||
* If a section has a zero value, it is omitted. | ||
@@ -1133,0 +1133,0 @@ * The hours, minutes and seconds will all have the same sign. |
@@ -90,3 +90,3 @@ /** | ||
const jsJiodaExports = { | ||
const jsJodaExports = { | ||
_, | ||
@@ -147,4 +147,4 @@ convert, | ||
const use = bindUse(jsJiodaExports); | ||
jsJiodaExports.use = use; | ||
const use = bindUse(jsJodaExports); | ||
jsJodaExports.use = use; | ||
@@ -151,0 +151,0 @@ export { |
@@ -888,7 +888,7 @@ /** | ||
* | ||
* @param {number} secondstoAdd - the seconds to add, may be negative | ||
* @param {number} secondsToAdd - the seconds to add, may be negative | ||
* @return {LocalTime} a {@link LocalTime} based on this time with the seconds added, not null | ||
*/ | ||
plusSeconds(secondstoAdd) { | ||
if (secondstoAdd === 0) { | ||
plusSeconds(secondsToAdd) { | ||
if (secondsToAdd === 0) { | ||
return this; | ||
@@ -898,3 +898,3 @@ } | ||
this._minute * LocalTime.SECONDS_PER_MINUTE + this._second; | ||
const newSofd = MathUtil.intMod((MathUtil.intMod(secondstoAdd, LocalTime.SECONDS_PER_DAY) + sofd + LocalTime.SECONDS_PER_DAY), LocalTime.SECONDS_PER_DAY); | ||
const newSofd = MathUtil.intMod((MathUtil.intMod(secondsToAdd, LocalTime.SECONDS_PER_DAY) + sofd + LocalTime.SECONDS_PER_DAY), LocalTime.SECONDS_PER_DAY); | ||
if (sofd === newSofd) { | ||
@@ -901,0 +901,0 @@ return this; |
@@ -13,3 +13,2 @@ /** | ||
import {DateTimeException, IllegalArgumentException, UnsupportedTemporalTypeException} from './errors'; | ||
import {DateTimeFormatterBuilder} from './format/DateTimeFormatterBuilder'; | ||
import {IsoChronology} from './chrono/IsoChronology'; | ||
@@ -73,7 +72,6 @@ import {Temporal} from './temporal/Temporal'; | ||
*/ | ||
// eslint-disable-next-line no-unused-vars | ||
getDisplayName(style, locale) { | ||
// TODO: | ||
throw new IllegalArgumentException('Pattern using (localized) text not implemented yet!'); | ||
//eslint-disable-next-line no-unreachable | ||
return new DateTimeFormatterBuilder().appendText(ChronoField.MONTH_OF_YEAR, style).toFormatter(locale).format(this); | ||
} | ||
@@ -80,0 +78,0 @@ |
@@ -437,3 +437,3 @@ /** | ||
* @param {!ZoneOffset} other - the other date to compare to, not null | ||
* @return {number} the comparator value, negative if less, postive if greater | ||
* @return {number} the comparator value, negative if less, positive if greater | ||
* @throws NullPointerException if {@link other} is null | ||
@@ -440,0 +440,0 @@ */ |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
3840168
96
46809
147