Socket
Socket
Sign inDemoInstall

js-joda

Package Overview
Dependencies
Maintainers
1
Versions
63
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

js-joda - npm Package Compare versions

Comparing version 0.3.14 to 0.9.1

benchmark/browser-init.js

184

CheatSheet.md

@@ -6,2 +6,53 @@ js-joda Cheat sheet

## Table of content
<!-- toc -->
- [Try it out](#try-it-out)
- [Consistent method prefixes](#consistent-method-prefixes)
- [Basic concepts](#basic-concepts)
- [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)
- [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)
- [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)
- [ZonedDateTime](#zoneddatetime)
* [The system default time zone](#the-system-default-time-zone)
* [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)
<!-- 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 [this webpage](http://pithu.github.io/js-joda/cheat-sheet.html).

@@ -96,4 +147,8 @@

```
### Get weeks of week based year, get year quarters and the day of quarter
```javascript
// get week of week based year as defined by ISO 8601 with a monday based week

@@ -179,11 +234,2 @@ d.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR); // 51

// set by a TemporalAdjuster lastDayOfMonth
d.with(TemporalAdjusters.lastDayOfMonth()) // 2016-12-31
// set by a TemporalAdjuster lastDayOfMonth
d.with(TemporalAdjusters.nextOrSame(DayOfWeek.SATURDAY)) // 2016-12-31
// set by a TemporalAdjuster next or same weekday
d.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY)) // 2016-12-25
```

@@ -259,3 +305,27 @@

### Adjust a date to another date
TemporalAdjusters provides 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
// 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
// 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
```
Find more adjusters in the TemporalAdjusters API documentation.
## LocalTime

@@ -371,3 +441,3 @@

### truncate a LocalTime instance
### Truncate a LocalTime instance

@@ -423,3 +493,3 @@ ```javascript

### Convert from a javascript Date or moment
### Convert a LocalTime from a javascript Date or moment

@@ -606,3 +676,3 @@ ```javascript

### truncate a LocalDateTime instance
### Truncate a LocalDateTime instance

@@ -678,3 +748,93 @@ ```javascript

## ZonedDateTime
ZonedDateTime represents a date-time with a time-zone in the ISO-8601 calendar system. Without the iana tzdb loaded,
ZonedDateTime only supports time-zones with a fixed Offset such as `UTC` or `UTC+02:00` and the system default time-zone `SYSTEM`.
### The system default time zone
The `SYSTEM` time-zone is a NON standard zone-id, that is introduced by js-joda because the javascript spec do not provide an api
for the system default zone-id. The javascript spec only provides the system default tome-zone offset for a point in the timeline
(Date.prototype.getTimezoneOffset()).
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 the other machine. Before a ZonedDateTime is exchanged,
it should be converted to a fixed offset zone.
```javascript
// get now with the default system time-zone
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
```
### Create a ZonedDateTime
```javascript
// 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
ZonedDateTime.now(ZoneId.UTC).toString(); // e.g. 2016-03-18T11:38:23.561Z
// 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]
// parse a date time with a time tone ISO String
ZonedDateTime.parse('2016-03-18T12:38:23.561+01:00[SYSTEM]');
ZonedDateTime.parse('2016-03-18T12:38:23.561+01:00');
ZonedDateTime.parse('2016-03-18T11:38:23.561Z');
ZonedDateTime.parse('2016-03-18T06:38:23.561-05:00[UTC-05:00]');
// create from a LocalDate(Time)
LocalDate.parse('2012-06-06').atStartOfDay().atZone(ZoneId.SYSTEM); // 2012-06-06T00:00+02:00[SYSTEM]
ZonedDateTime.of(LocalDateTime.parse('2012-06-06T00:00'), ZoneId.SYSTEM) // 2012-06-06T00:00+02:00[SYSTEM]
ZonedDateTime.of(LocalDate.parse('2012-06-06'), LocalTime.MIDNIGHT, ZoneId.SYSTEM) // 2012-06-06T00:00+02:00[SYSTEM]
// create by Instant
ZonedDateTime.ofInstant(Instant.now(), ZoneId.SYSTEM) // current system time
```
### Switch timezones
```javascript
var d = LocalDate.of(2016, 3, 18)
var zdt = d.atTime(LocalTime.NOON).atZone(ZoneId.of('UTC-05:00')) // 2016-03-18T12:00-05:00[UTC-05:00]
// switch timezone retaining the local date-time if possible
zdt.withZoneSameLocal(ZoneId.UTC); // 2016-03-18T12:00Z
// switch timezone and retain the instant
zdt.withZoneSameInstant(ZoneId.UTC); // 2016-03-18T17:00Z
```
### Get and manipulate values from a ZonedDateTime
Check the examples for LocalDate and LocalDateTime. ZonedDateTime implements the same methods as LocalDateTime
for getting or setting values.
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.
```javascript
// assume the system default time zone is CET and its 2016-03-18 at noon local time.
var zdt = ZonedDateTime.now(); // 2016-03-18T12:00+01:00[SYSTEM]
// adding a date unit of 2 weeks (crossing a daylight saving transition)
zdt.plusWeeks(2); // still noon: 2016-04-01T12:00+02:00[SYSTEM]
// adding a time unit of 2 weeks (2 * 7 * 24)
zdt.plusHours(2 * 7 * 24); // 1 pm: 2016-04-01T13:00+02:00[SYSTEM]
```
## Period

@@ -681,0 +841,0 @@

6

package.json
{
"name": "js-joda",
"version": "0.3.14",
"version": "0.9.1",
"description": "a date and time library for javascript",

@@ -19,3 +19,3 @@ "repository": {

"build-dist": "./node_modules/.bin/webpack --progress --colors --bail && DIST_MIN=1 ./node_modules/.bin/webpack --progress --colors --bail",
"build-readme2html": "mkdir -p build && ./node_modules/.bin/marked -i README.md -o build/README.hml && ./node_modules/.bin/marked -i CheatSheet.md -o build/CheatSheet.hml "
"build-readme2html": "mkdir -p build && ./node_modules/.bin/marked -i README.md -o build/README.html && ./node_modules/.bin/markdown-toc -i CheatSheet.md && ./node_modules/.bin/marked -i CheatSheet.md -o build/CheatSheet.html"
},

@@ -34,2 +34,3 @@ "keywords": [

"babel-preset-es2015": "^6.6.0",
"babel-preset-es2015-loose": "^7.0.0",
"chai": "^3.5.0",

@@ -47,2 +48,3 @@ "coveralls": "^2.11.8",

"karma-webpack": "^1.7.0",
"markdown-toc": "^0.12.3",
"marked": "^0.3.5",

@@ -49,0 +51,0 @@ "mocha": "^2.4.5",

@@ -6,2 +6,3 @@ /*

import {_init as ZoneOffsetInit} from './ZoneOffset';
import {_init as DayOfWeekInit} from './DayOfWeek';

@@ -16,3 +17,3 @@ import {_init as DurationInit} from './Duration';

import {_init as YearInit} from './Year';
import {_init as ZoneOffsetInit} from './ZoneOffset';
import {_init as ZonedDateTimeInit} from './ZonedDateTime';
import {_init as IsoChronologyInit} from './chrono/IsoChronology';

@@ -23,4 +24,6 @@ import {_init as DateTimeFormatterInit} from './format/DateTimeFormatter';

import {_init as IsoFieldsInit} from './temporal/IsoFields';
import {_init as TemporalQueriesInit} from './temporal/TemporalQueries';
import {_init as TemporalQueriesInit} from './temporal/TemporalQueriesFactory';
import {_init as ZoneIdInit} from './ZoneIdFactory';
var isInit = false;

@@ -50,2 +53,4 @@

ZoneOffsetInit();
ZonedDateTimeInit();
ZoneIdInit();
IsoChronologyInit();

@@ -52,0 +57,0 @@ DateTimeFormatterInit();

@@ -32,3 +32,3 @@ /**

export function abstractMethodFail(methodName){
throw new TypeError('abstract mehod ' + methodName + 'is not implemented');
throw new TypeError('abstract mehod "' + methodName + '" is not implemented');
}

@@ -116,3 +116,3 @@ /*

* @param {ZoneOffset} offset the offset to use for the conversion, not null
* @return the number of seconds from the epoch of 1970-01-01T00:00:00Z
* @return {number} the number of seconds from the epoch of 1970-01-01T00:00:00Z
*/

@@ -119,0 +119,0 @@ toEpochSecond(offset) {

@@ -7,3 +7,3 @@ /**

import {abstractMethodFail} from './assert';
import {abstractMethodFail, requireNonNull} from './assert';
import {Instant} from './Instant';

@@ -64,3 +64,3 @@ import {ZoneId} from './ZoneId';

static systemUTC() {
return new SystemUTCClock();
return new SystemClock(ZoneOffset.UTC);
}

@@ -84,6 +84,15 @@

static systemDefaultZone() {
return new SystemDefaultClock();
return new SystemClock(ZoneId.systemDefault());
}
/**
*
* @param {ZoneId} zone
* @return {Clock} a clock that uses the specified time zone
*/
static system(zone){
return new SystemClock(zone);
}
/**
* Obtains a clock that always returns the same instant.

@@ -140,3 +149,29 @@ * <p>

/**
* Implementation of a clock that always returns the latest time from
* {@link Date#getTime()}.
*/
class SystemClock extends Clock {
/**
*
* @param {!ZoneId} zone
*/
constructor(zone){
requireNonNull(zone, 'zone');
super();
this._zone = zone;
}
/**
*
* @returns {!ZoneId}
*/
zone() {
return this._zone;
}
/**
*
* @returns {number}
*/
millis() {

@@ -146,33 +181,18 @@ return new Date().getTime();

/**
*
* @returns {Instant}
*/
instant() {
return Instant.ofEpochMilli(this.millis());
}
}
/**
* Implementation of a clock that always returns the latest time from
* {@link Date#getTime()}.
*/
class SystemUTCClock extends SystemClock{
zone(){
return ZoneOffset.UTC;
}
/**
*
* @returns {string}
*/
toString(){
return 'SystemClock[UTC]';
return 'SystemClock[' + this._zone.toString() + ']';
}
}
/**
* Implementation of a clock that always returns the latest time from
* sytem default Zone {@link Date#getTime()} and {@link Date#getTimeZoneOffset()}.
*/
class SystemDefaultClock extends SystemClock{
zone(){
return ZoneId.systemDefault();
}
toString(){
return 'SystemClock[default]';
}
}

@@ -179,0 +199,0 @@

@@ -126,3 +126,3 @@ /*

throw new DateTimeException('Unable to obtain DayOfWeek from TemporalAccessor: ' +
temporal + ', type ' + temporal.name(), ex);
temporal + ', type ' + (temporal.constructor != null ? temporal.constructor.name : ''), ex);
} else {

@@ -129,0 +129,0 @@ throw ex;

@@ -41,2 +41,18 @@ /*

/**
* Creates a new instance of the builder with a single field-value.
* <p>
* This is equivalent to using {@link #addFieldValue(TemporalField, long)} on an empty builder.
*
* @param {TemporalField} field - the field to add, not null
* @param {number} value - the value to add, not null
* @return {DateTimeBuilder}
*/
static create(field, value) {
var dtb = new DateTimeBuilder();
dtb._addFieldValue(field, value);
return dtb;
}
constructor(){

@@ -43,0 +59,0 @@ super();

@@ -484,2 +484,18 @@ /**

DateTimeFormatter.ISO_OFFSET_DATE_TIME = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
.appendOffsetId()
.toFormatter(ResolverStyle.STRICT).withChronology(IsoChronology.INSTANCE);
DateTimeFormatter.ISO_ZONED_DATE_TIME = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
.optionalStart()
.appendLiteral('[')
.parseCaseSensitive()
.appendZoneId()
// .appendZoneRegionId()
.appendLiteral(']')
.toFormatter(ResolverStyle.STRICT).withChronology(IsoChronology.INSTANCE);
DateTimeFormatter.PARSED_EXCESS_DAYS = createTemporalQuery('PARSED_EXCESS_DAYS', (temporal) => {

@@ -486,0 +502,0 @@ if (temporal instanceof DateTimeBuilder) {

@@ -7,3 +7,3 @@ /*

import {assert} from '../assert';
import {assert, requireNonNull} from '../assert';

@@ -180,2 +180,15 @@ import {DateTimeBuilder} from './DateTimeBuilder';

/**
* Stores the parsed zone.
* <p>
* This stores the zone that has been parsed.
* No validation is performed other than ensuring it is not null.
*
* @param {ZoneId} zone the parsed zone, not null
*/
setParsedZone(zone) {
requireNonNull(zone, 'zone');
this.currentParsed().zone = zone;
}
getParsed(field) {

@@ -182,0 +195,0 @@ return this.currentParsed().fieldValues.get(field);

@@ -62,2 +62,17 @@ /*

/**
* Gets a value using a query.
*
* @param {TemporalQuery} query the query to use, not null
* @return {*} the result, null if not found and optional is true
* @throws DateTimeException if the type is not available and the section is not optional
*/
getValueQuery(query) {
var result = this._temporal.query(query);
if (result == null && this._optional === 0) {
throw new DateTimeException('Unable to extract value: ' + this._temporal);
}
return result;
}
/**
* Gets the value of the specified field.

@@ -64,0 +79,0 @@ *

@@ -26,2 +26,6 @@ /*

put(key, val) {
return this.set(key, val);
}
set(key, val) {

@@ -28,0 +32,0 @@ this._map[key.name()] = val;

@@ -16,2 +16,7 @@ /*

appendChar(str){
this._str += str[0];
return this;
}
insert(offset, str){

@@ -18,0 +23,0 @@ this._str = this._str.slice(0, offset) + str + this._str.slice(offset);

@@ -342,13 +342,3 @@ /**

get(field) {
if (field instanceof ChronoField) {
switch (field) {
case ChronoField.NANO_OF_SECOND: return this._nanos;
case ChronoField.MICRO_OF_SECOND: return MathUtil.intDiv(this._nanos, 1000);
case ChronoField.MILLI_OF_SECOND: return MathUtil.intDiv(this._nanos, NANOS_PER_MILLI);
case ChronoField.INSTANT_SECONDS:
ChronoField.INSTANT_SECONDS.checkValidIntValue(this._seconds);
}
throw new UnsupportedTemporalTypeException('Unsupported field: ' + field);
}
return this.range(field).checkValidIntValue(field.getFrom(this), field);
return this.getLong(field);
}

@@ -355,0 +345,0 @@

@@ -17,3 +17,5 @@ /**

export { Year } from './Year';
export { ZonedDateTime } from './ZonedDateTime';
export { ZoneOffset } from './ZoneOffset';
export { ZoneId } from './ZoneId';

@@ -20,0 +22,0 @@ export {nativeJs} from './temporal/NativeJsTemporal';

@@ -396,2 +396,46 @@ /**

/**
* Adjusts the specified temporal object to have this month-of-year.
* <p>
* This returns a temporal object of the same observable type as the input
* with the month-of-year changed to be the same as this.
* <p>
* The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}
* passing {@link ChronoField#MONTH_OF_YEAR} as the field.
* If the specified temporal object does not use the ISO calendar system then
* a {@code DateTimeException} is thrown.
* <p>
* In most cases, it is clearer to reverse the calling pattern by using
* {@link Temporal#with(TemporalAdjuster)}:
* <pre>
* // these two lines are equivalent, but the second approach is recommended
* temporal = thisMonth.adjustInto(temporal);
* temporal = temporal.with(thisMonth);
* </pre>
* <p>
* For example, given a date in May, the following are output:
* <pre>
* dateInMay.with(JANUARY); // four months earlier
* dateInMay.with(APRIL); // one months earlier
* dateInMay.with(MAY); // same date
* dateInMay.with(JUNE); // one month later
* dateInMay.with(DECEMBER); // seven months later
* </pre>
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param {Temporal} temporal - the target object to be adjusted, not null
* @return {Temporal} the adjusted object, not null
* @throws DateTimeException if unable to make the adjustment
* @throws ArithmeticException if numeric overflow occurs
*/
adjustInto(temporal) {
/* we support only ISO for now
if (Chronology.from(temporal).equals(IsoChronology.INSTANCE) === false) {
throw new DateTimeException('Adjustment only supported on ISO date-time');
}
*/
return temporal.with(ChronoField.MONTH_OF_YEAR, this.value());
}
/**
* replacement for enum values

@@ -398,0 +442,0 @@ * @return {Month[]}

@@ -6,6 +6,8 @@ /**

*/
import {MAX_SAFE_INTEGER, MIN_SAFE_INTEGER} from '../MathUtil';
import {ChronoUnit} from './ChronoUnit';
import { TemporalField } from './TemporalField';
import { ValueRange } from './ValueRange';
import {TemporalField} from './TemporalField';
import {ValueRange} from './ValueRange';
import {Year} from '../Year';

@@ -12,0 +14,0 @@

@@ -87,3 +87,3 @@ /*

*
* <h3>Static properties of Class {@link ChronoField}</h3>
* <h3>Static properties of Class {@link IsoFields}</h3>
*

@@ -90,0 +90,0 @@ * IsoFields.DAY_OF_QUARTER

@@ -6,5 +6,7 @@ /**

*/
import {UnsupportedTemporalTypeException} from '../errors';
import {ChronoField} from './ChronoField';
import {TemporalQueries} from './TemporalQueries';
import {UnsupportedTemporalTypeException} from '../errors';

@@ -11,0 +13,0 @@ export class TemporalAccessor {

@@ -7,9 +7,2 @@ /**

import {ChronoField} from './ChronoField';
import {createTemporalQuery} from './TemporalQuery';
import {LocalDate} from '../LocalDate';
import {LocalTime} from '../LocalTime';
import {ZoneOffset} from '../ZoneOffset';
/**

@@ -230,64 +223,1 @@ * Common implementations of {@code TemporalQuery}.

}
export function _init() {
//-----------------------------------------------------------------------
/**
* A strict query for the {@code ZoneId}.
*/
TemporalQueries.ZONE_ID = createTemporalQuery('ZONE_ID', (temporal) => {
return temporal.query(TemporalQueries.ZONE_ID);
});
/**
* A query for the {@code Chronology}.
*/
TemporalQueries.CHRONO = createTemporalQuery('CHRONO', (temporal) => {
return temporal.query(TemporalQueries.CHRONO);
});
/**
* A query for the smallest supported unit.
*/
TemporalQueries.PRECISION = createTemporalQuery('PRECISION', (temporal) => {
return temporal.query(TemporalQueries.PRECISION);
});
//-----------------------------------------------------------------------
/**
* A query for {@code ZoneOffset} returning null if not found.
*/
TemporalQueries.OFFSET = createTemporalQuery('OFFSET', (temporal) => {
if (temporal.isSupported(ChronoField.OFFSET_SECONDS)) {
return ZoneOffset.ofTotalSeconds(temporal.get(TemporalQueries.OFFSET_SECONDS));
}
return null;
});
/**
* A lenient query for the {@code ZoneId}, falling back to the {@code ZoneOffset}.
*/
TemporalQueries.ZONE = createTemporalQuery('ZONE', (temporal) => {
var zone = temporal.query(TemporalQueries.ZONE_ID);
return (zone != null ? zone : temporal.query(TemporalQueries.OFFSET));
});
/**
* A query for {@code LocalDate} returning null if not found.
*/
TemporalQueries.LOCAL_DATE = createTemporalQuery('LOCAL_DATE', (temporal) => {
if (temporal.isSupported(ChronoField.EPOCH_DAY)) {
return LocalDate.ofEpochDay(temporal.getLong(TemporalQueries.EPOCH_DAY));
}
return null;
});
/**
* A query for {@code LocalTime} returning null if not found.
*/
TemporalQueries.LOCAL_TIME = createTemporalQuery('LOCAL_TIME', (temporal) => {
if (temporal.isSupported(ChronoField.NANO_OF_DAY)) {
return LocalTime.ofNanoOfDay(temporal.getLong(TemporalQueries.NANO_OF_DAY));
}
return null;
});
}

@@ -21,3 +21,3 @@ /*

offsetOfInstant(instant){
var offsetInMinutes = new Date().getTimezoneOffset(instant.toEpochMilli());
var offsetInMinutes = new Date(instant.toEpochMilli()).getTimezoneOffset();
return ZoneOffset.ofTotalMinutes(offsetInMinutes * -1);

@@ -27,3 +27,11 @@ }

/**
* This implementation is NOT returning the best value in a gap or overlap situation
* as specified at {@link ZoneRules.offsetOfLocalDateTime}.
*
* The calculated offset depends Date.prototype.getTimezoneOffset and its not specified
* at the ECMA-262 specification how to handle daylight savings gaps/ overlaps.
*
* The Chrome Browser version 49 is returning the next transition offset in a gap/overlap situation,
* other browsers/ engines might do it in the same way.
*
* @param {LocalDateTime} localDateTime

@@ -34,6 +42,18 @@ * @returns {ZoneOffset}

var epochMilli = localDateTime.toEpochSecond(ZoneOffset.UTC) * 1000;
var offsetInMinutes = new Date().getTimezoneOffset(epochMilli);
return ZoneOffset.ofTotalMinutes(offsetInMinutes * -1);
var offsetInMinutesBeforePossibleTransition = new Date(epochMilli).getTimezoneOffset();
var epochMilliSystemZone = epochMilli + offsetInMinutesBeforePossibleTransition * 60000;
var offsetInMinutesAfterPossibleTransition = new Date(epochMilliSystemZone).getTimezoneOffset();
return ZoneOffset.ofTotalMinutes(offsetInMinutesAfterPossibleTransition * -1);
}
/**
*
* @param {LocalDateTime} dateTime
* @param {ZoneOffset} offset
* @return {boolean}
*/
isValidOffset(dateTime, offset) {
return this.offsetOfLocalDateTime(dateTime).equals(offset);
}
//-----------------------------------------------------------------------

@@ -58,5 +78,5 @@ /**

toString() {
return 'SystemDefaultZoneRules()';
return 'SYSTEM';
}
}

@@ -98,2 +98,17 @@ /*

/**
* Checks if the offset date-time is valid for these rules.
* <p>
* To be valid, the local date-time must not be in a gap and the offset
* must match the valid offsets.
*
* @param {LocalDateTime} localDateTime - the date-time to check, not null, but null
* may be ignored if the rules have a single offset for all instants
* @param {ZoneOffset} offset - the offset to check, null returns false
* @return {boolean} true if the offset date-time is valid for these rules
*/
isValidOffset(localDateTime, offset){
abstractMethodFail('ZoneRules.isValidOffset');
}
}

@@ -124,2 +139,12 @@

/**
*
* @param {LocalDateTime} LocalDateTime
* @param {ZoneOffset} offset
* @return {boolean}
*/
isValidOffset(dateTime, offset) {
return this._offset.equals(offset);
}
//-----------------------------------------------------------------------

@@ -126,0 +151,0 @@ /**

@@ -8,21 +8,9 @@ /*

import {abstractMethodFail} from './assert';
import {StringUtil} from './StringUtil';
import {SystemDefaultZoneRules} from './zone/SystemDefaultZoneRules';
import {Instant} from './Instant';
export class ZoneId {
//-----------------------------------------------------------------------
/**
* Gets the system default time-zone.
* <p>
*
* @return {ZoneId} the zone ID, not null
*/
static systemDefault() {
return zoneSystemDefaultInstance;
}
//-----------------------------------------------------------------------
/**
* Gets the time-zone rules for this ID allowing calculations to be performed.

@@ -51,18 +39,65 @@ * <p>

}
/**
* Normalizes the time-zone ID, returning a {@code ZoneOffset} where possible.
* <p>
* The returns a normalized {@code ZoneId} that can be used in place of this ID.
* The result will have {@code ZoneRules} equivalent to those returned by this object,
* however the ID returned by {@code getId()} may be different.
* <p>
* The normalization checks if the rules of this {@code ZoneId} have a fixed offset.
* If they do, then the {@code ZoneOffset} equal to that offset is returned.
* Otherwise {@code this} is returned.
*
* @return {ZoneId} the time-zone unique ID, not null
*/
normalized() {
var rules = this.rules();
if (rules.isFixedOffset()) {
return rules.offset(Instant.EPOCH);
}
//try {
//} catch (ZoneRulesException ex) {
// // ignore invalid objects
//}
return this;
}
class ZoneIdSystemDefault extends ZoneId {
//-----------------------------------------------------------------------
/**
* Checks if this time-zone ID is equal to another time-zone ID.
* <p>
* The comparison is based on the ID.
*
* @param {*} other the object to check, null returns false
* @return {boolean} true if this is equal to the other time-zone ID
*/
equals(other) {
if (this === other) {
return true;
}
if (other instanceof ZoneId) {
return this.id() === other.id();
}
return false;
}
constructor(){
super();
this._rules = new SystemDefaultZoneRules();
}
/**
* A hash code for this time-zone ID.
*
* @return {number} a suitable hash code
*/
hashCode() {
return StringUtil.hashCode(this.id());
}
rules(){
return this._rules;
}
//-----------------------------------------------------------------------
/**
* Outputs this zone as a {@code String}, using the ID.
*
* @return {string} a string representation of this time-zone ID, not null
*/
toString() {
return this.id();
}
}
var zoneSystemDefaultInstance = new ZoneIdSystemDefault();

@@ -7,3 +7,5 @@ /**

import {requireNonNull} from './assert';
import {DateTimeException} from './errors';
import {MathUtil} from './MathUtil';

@@ -13,7 +15,10 @@ import {LocalTime} from './LocalTime';

import {ChronoField} from './temporal/ChronoField';
import {TemporalQueries} from './temporal/TemporalQueries';
import {ZoneRules} from './zone/ZoneRules';
var SECONDS_CACHE = {};
var ID_CACHE = {};
/**

@@ -42,2 +47,3 @@ *

this._rules = ZoneRules.of(this);
this._id = ZoneOffset._buildId(totalSeconds);
}

@@ -54,2 +60,34 @@

/**
*
* @returns {string}
*/
id() {
return this._id;
}
/**
*
* @param {number} totalSeconds
* @returns {string}
*/
static _buildId(totalSeconds) {
if (totalSeconds === 0) {
return 'Z';
} else {
var absTotalSeconds = Math.abs(totalSeconds);
var absHours = MathUtil.intDiv(absTotalSeconds, LocalTime.SECONDS_PER_HOUR);
var absMinutes = MathUtil.intMod(MathUtil.intDiv(absTotalSeconds, LocalTime.SECONDS_PER_MINUTE), LocalTime.MINUTES_PER_HOUR);
var buf = '' + (totalSeconds < 0 ? '-' : '+')
+ (absHours < 10 ? '0' : '') + (absHours)
+ (absMinutes < 10 ? ':0' : ':') + (absMinutes);
var absSeconds = MathUtil.intMod(absTotalSeconds, LocalTime.SECONDS_PER_MINUTE);
if (absSeconds !== 0) {
buf += (absSeconds < 10 ? ':0' : ':') + (absSeconds);
}
return buf;
}
}
/**
*

@@ -101,3 +139,106 @@ * @param {number} totalSeconds

//-----------------------------------------------------------------------
/**
* Obtains an instance of {@code ZoneOffset} using the ID.
* <p>
* This method parses the string ID of a {@code ZoneOffset} to
* return an instance. The parsing accepts all the formats generated by
* {@link #getId()}, plus some additional formats:
* <p><ul>
* <li>{@code Z} - for UTC
* <li>{@code +h}
* <li>{@code +hh}
* <li>{@code +hh:mm}
* <li>{@code -hh:mm}
* <li>{@code +hhmm}
* <li>{@code -hhmm}
* <li>{@code +hh:mm:ss}
* <li>{@code -hh:mm:ss}
* <li>{@code +hhmmss}
* <li>{@code -hhmmss}
* </ul><p>
* Note that &plusmn; means either the plus or minus symbol.
* <p>
* The ID of the returned offset will be normalized to one of the formats
* described by {@link #getId()}.
* <p>
* The maximum supported range is from +18:00 to -18:00 inclusive.
*
* @param {string} offsetId the offset ID, not null
* @return {ZoneOffset} the zone-offset, not null
* @throws DateTimeException if the offset ID is invalid
*/
static of(offsetId) {
requireNonNull(offsetId, 'offsetId');
// "Z" is always in the cache
var offset = ID_CACHE[offsetId];
if (offset != null) {
return offset;
}
// parse - +h, +hh, +hhmm, +hh:mm, +hhmmss, +hh:mm:ss
var hours, minutes, seconds;
switch (offsetId.length) {
case 2:
offsetId = offsetId[0] + '0' + offsetId[1]; // fallthru
case 3:
hours = ZoneOffset._parseNumber(offsetId, 1, false);
minutes = 0;
seconds = 0;
break;
case 5:
hours = ZoneOffset._parseNumber(offsetId, 1, false);
minutes = ZoneOffset._parseNumber(offsetId, 3, false);
seconds = 0;
break;
case 6:
hours = ZoneOffset._parseNumber(offsetId, 1, false);
minutes = ZoneOffset._parseNumber(offsetId, 4, true);
seconds = 0;
break;
case 7:
hours = ZoneOffset._parseNumber(offsetId, 1, false);
minutes = ZoneOffset._parseNumber(offsetId, 3, false);
seconds = ZoneOffset._parseNumber(offsetId, 5, false);
break;
case 9:
hours = ZoneOffset._parseNumber(offsetId, 1, false);
minutes = ZoneOffset._parseNumber(offsetId, 4, true);
seconds = ZoneOffset._parseNumber(offsetId, 7, true);
break;
default:
throw new DateTimeException('Invalid ID for ZoneOffset, invalid format: ' + offsetId);
}
var first = offsetId[0];
if (first !== '+' && first !== '-') {
throw new DateTimeException('Invalid ID for ZoneOffset, plus/minus not found when expected: ' + offsetId);
}
if (first === '-') {
return ZoneOffset.ofHoursMinutesSeconds(-hours, -minutes, -seconds);
} else {
return ZoneOffset.ofHoursMinutesSeconds(hours, minutes, seconds);
}
}
/**
* Parse a two digit zero-prefixed number.
*
* @param {string} offsetId - the offset ID, not null
* @param {number} pos - the position to parse, valid
* @param {boolean} precededByColon - should this number be prefixed by a precededByColon
* @return {number} the parsed number, from 0 to 99
*/
static _parseNumber(offsetId, pos, precededByColon) {
if (precededByColon && offsetId[pos - 1] !== ':') {
throw new DateTimeException('Invalid ID for ZoneOffset, colon not found when expected: ' + offsetId);
}
var ch1 = offsetId[pos];
var ch2 = offsetId[pos + 1];
if (ch1 < '0' || ch1 > '9' || ch2 < '0' || ch2 > '9') {
throw new DateTimeException('Invalid ID for ZoneOffset, non numeric characters found: ' + offsetId);
}
return (ch1.charCodeAt(0) - 48) * 10 + (ch2.charCodeAt(0) - 48);
}
/**
*

@@ -156,2 +297,3 @@ * @param {number} hours

SECONDS_CACHE[totalSecs] = result;
ID_CACHE[result.id()] = result;
}

@@ -176,4 +318,135 @@ return result;

/**
* Gets the value of the specified field from this offset as an {@code int}.
* <p>
* This queries this offset for the value for the specified field.
* The returned value will always be within the valid range of values for the field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
* <p>
* If the field is a {@link ChronoField} then the query is implemented here.
* The {@code OFFSET_SECONDS} field returns the value of the offset.
* All other {@code ChronoField} instances will throw a {@code DateTimeException}.
* <p>
* If the field is not a {@code ChronoField}, then the result of this method
* is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
* passing {@code this} as the argument. Whether the value can be obtained,
* and what the value represents, is determined by the field.
*
* @param {TemporalField} field - the field to get, not null
* @return {number} the value for the field
* @throws DateTimeException if a value for the field cannot be obtained
* @throws ArithmeticException if numeric overflow occurs
*/
get(field) {
return this.getLong(field);
}
/**
* Gets the value of the specified field from this offset as a {@code long}.
* <p>
* This queries this offset for the value for the specified field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
* <p>
* If the field is a {@link ChronoField} then the query is implemented here.
* The {@code OFFSET_SECONDS} field returns the value of the offset.
* All other {@code ChronoField} instances will throw a {@code DateTimeException}.
* <p>
* If the field is not a {@code ChronoField}, then the result of this method
* is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
* passing {@code this} as the argument. Whether the value can be obtained,
* and what the value represents, is determined by the field.
*
* @param {TemporalField} field - the field to get, not null
* @return {number} the value for the field
* @throws DateTimeException if a value for the field cannot be obtained
* @throws ArithmeticException if numeric overflow occurs
*/
getLong(field) {
if (field === ChronoField.OFFSET_SECONDS) {
return this._totalSeconds;
} else if (field instanceof ChronoField) {
throw new DateTimeException('Unsupported field: ' + field);
}
return field.getFrom(this);
}
//-----------------------------------------------------------------------
/**
* Queries this offset using the specified query.
* <p>
* This queries this offset using the specified query strategy object.
* The {@code TemporalQuery} object defines the logic to be used to
* obtain the result. Read the documentation of the query to understand
* what the result of this method will be.
* <p>
* The result of this method is obtained by invoking the
* {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the
* specified query passing {@code this} as the argument.
*
* @param {TemporalQuery} query - the query to invoke, not null
* @return {*} the query result, null may be returned (defined by the query)
* @throws DateTimeException if unable to query (defined by the query)
* @throws ArithmeticException if numeric overflow occurs (defined by the query)
*/
query(query) {
requireNonNull(query, 'query');
if (query === TemporalQueries.offset() || query === TemporalQueries.zone()) {
return this;
} else if (query === TemporalQueries.localDate() || query === TemporalQueries.localTime() ||
query === TemporalQueries.precision() || query === TemporalQueries.chronology() || query === TemporalQueries.zoneId()) {
return null;
}
return query.queryFrom(this);
}
/**
* Adjusts the specified temporal object to have the same offset as this object.
* <p>
* This returns a temporal object of the same observable type as the input
* with the offset changed to be the same as this.
* <p>
* The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}
* passing {@link ChronoField#OFFSET_SECONDS} as the field.
* <p>
* In most cases, it is clearer to reverse the calling pattern by using
* {@link Temporal#with(TemporalAdjuster)}:
* <pre>
* // these two lines are equivalent, but the second approach is recommended
* temporal = thisOffset.adjustInto(temporal);
* temporal = temporal.with(thisOffset);
* </pre>
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param {Temporal} temporal - the target object to be adjusted, not null
* @return {Temporal} the adjusted object, not null
* @throws DateTimeException if unable to make the adjustment
* @throws ArithmeticException if numeric overflow occurs
*/
adjustInto(temporal) {
return temporal.with(ChronoField.OFFSET_SECONDS, this._totalSeconds);
}
/**
* Compares this offset to another offset in descending order.
* <p>
* The offsets are compared in the order that they occur for the same time
* of day around the world. Thus, an offset of {@code +10:00} comes before an
* offset of {@code +09:00} and so on down to {@code -18:00}.
* <p>
* The comparison is "consistent with equals", as defined by {@link Comparable}.
*
* @param {!ZoneOffset} other - the other date to compare to, not null
* @return {number} the comparator value, negative if less, postive if greater
* @throws NullPointerException if {@code other} is null
*/
compareTo(other) {
requireNonNull(other, 'other');
return other._totalSeconds - this._totalSeconds;
}
/**
* Checks if this offset is equal to another offset.

@@ -196,3 +469,25 @@ *

}
/**
* @return {number}
*/
hashCode(){
return this._totalSeconds;
}
/**
*
* @returns {string}
*/
id() {
return this._id;
}
/**
*
* @returns {string}
*/
toString(){
return this._id;
}
}

@@ -199,0 +494,0 @@

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 not supported yet

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

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc