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.10 to 0.3.11

119

CheatSheet.md

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

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).
## Consistent method prefixes

@@ -434,3 +436,3 @@

### Get values from LocalTime
### Get values from LocalDateTime

@@ -625,4 +627,115 @@ ```javascript

## Period and Duration
## Period
...
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
Period.parse('P1Y10M').toString(); // 'P1Y10M'
// obtain a Period of 10 years, 5 month and 30 days
Period.of(10, 5, 30).toString(); // "P10Y5M30D"
// 10 years
Period.ofYears(10).toString(); // "P10Y"
// add 45 days to a Period
Period.ofYears(10).plusDays(45).toString(); // "P10Y45D"
// normalize a Period of years and month
Period.of(1, 37, 0).normalized().toString(); // "P4Y1M"
// add/ subtract from a Period
Period.ofYears(10).plusMonths(10).minusDays(42).toString(); // "P10Y10M-42D"
// add a Period to LocalDate
var p = Period.ofMonths(1);
LocalDate.parse('2012-12-12').plus(p); // '2013-01-12';
LocalDate.parse('2012-01-31').plus(p); // '2012-02-29';
LocalDateTime.parse('2012-05-31T12:00').plus(p); // '2012-06-30T12:00';
// calculate the Period between two Dates
Period.between(LocalDate.parse('2012-06-30'), LocalDate.parse('2012-08-31')); // "P2M1D"
```
## Duration
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"
// obtain a Duration of 10 days (10 x 24 hours)
Duration.ofDays(10).toString(); // "PT240H"
// 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'
// calculate the durations beetween to time based temporals
var dt1 = LocalDateTime.parse('2012-12-24T12:00');
Duration.between(dt1, dt1.plusHours(10)).toString(); // "PT10H"
```
## Customize js-joda
js-joda is easy extend-able, it allows you to create your own custom domain models or formatter. check the temporal interface documentation
at temporal directory for more information.
### Custom temporal adjuster
```javascript
// 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'
```
### Custom temporal fields and temporal units
a good point to start is temporal/IsoFields as an example how to implement fields and units for an ISO week based year.
// TODO temporal/IsoFields is not yet migrated to js-joda, check org.threeten.bp.temporal.IsoFields for now.
### Custom formatter and queries
The following example, is a kind of the opposite of a domain driven approach.
It 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.
```javascript
// build a custom date time formatter where the time field is optional
var b = new DateTimeFormatterBuilder().parseCaseInsensitive()
b.append(DateTimeFormatter.ISO_LOCAL_DATE)
b.optionalStart()
b.appendLiteral('T').append(DateTimeFormatter.ISO_LOCAL_TIME)
var OPTIONAL_FORMATTER = b.toFormatter();
// 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)
}
}
localDate = OPTIONAL_FORMATTER.parse('2012-12-24', dateOrDateTimeQuery);
localDateTime = OPTIONAL_FORMATTER.parse('2012-12-24T23:59', dateOrDateTimeQuery);
```

5

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

@@ -50,6 +50,3 @@ "repository": {

},
"dependencies": {
"es6-error": "^2.0.2"
},
"license": "BSD-3-Clause"
}

@@ -30,1 +30,5 @@ /**

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

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

*/
import {abstractMethodFail} from './assert';
import {Instant} from './Instant';

@@ -116,3 +118,3 @@ import {ZoneOffset} from './ZoneOffset';

millis(){
throw new TypeError('millis() function is not implemented');
abstractMethodFail('millis');
}

@@ -128,3 +130,3 @@

instant(){
throw new TypeError('instant() function is not implemented');
abstractMethodFail('instant');
}

@@ -142,3 +144,3 @@

offset(){
throw new TypeError('offset() function is not implemented');
abstractMethodFail('offset');
}

@@ -145,0 +147,0 @@ }

/*
* @copyright (c) 2016, Philipp Thuerwaechter & Pattrick Hueper
* @copyright (c) 2016, Philipp Thuerwaechter & Pattrick Hueper
* @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos

@@ -4,0 +4,0 @@ * @license BSD-3-Clause (see LICENSE in the root directory of this source tree)

@@ -5,52 +5,43 @@ /**

*/
import ExtendableError from 'es6-error';
export class DateTimeException extends ExtendableError {
constructor(message = 'DateTimeException', cause = null) {
let msg = message;
if (cause !== null && cause instanceof Error) {
msg += '\n-------\nCaused by: ' + cause.stack + '\n-------\n';
function createErrorType(name, init, superErrorClass = Error) {
function E(message) {
if (!Error.captureStackTrace){
this.stack = (new Error()).stack;
} else {
Error.captureStackTrace(this, this.constructor);
}
super(msg);
}
}
this.message = message;
init && init.apply(this, arguments);
export class DateTimeParseException extends ExtendableError {
constructor(message = 'DateTimeParseException', text = '', index = 0, cause = null) {
let msg = message + ': ' + text + ', at index: ' + index;
if (cause !== null && cause instanceof Error) {
msg += '\n-------\nCaused by: ' + cause.stack + '\n-------\n';
}
super(msg);
}
E.prototype = new superErrorClass();
E.prototype.name = name;
E.prototype.constructor = E;
return E;
}
export class UnsupportedTemporalTypeException extends DateTimeException {
constructor(message = 'UnsupportedTemporalTypeException') {
super(message);
}
}
export var DateTimeException = createErrorType('DateTimeException', messageWithCause);
export var DateTimeParseException = createErrorType('DateTimeParseException', messageForDateTimeParseException);
export var UnsupportedTemporalTypeException = createErrorType('UnsupportedTemporalTypeException', null, DateTimeException);
export var ArithmeticException = createErrorType('ArithmeticException');
export var IllegalArgumentException = createErrorType('IllegalArgumentException');
export var IllegalStateException = createErrorType('IllegalStateException');
export var NullPointerException = createErrorType('NullPointerException');
export class ArithmeticException extends ExtendableError {
constructor(message = 'ArithmeticException') {
super(message);
function messageWithCause(message, cause = null) {
let msg = message || this.name;
if (cause !== null && cause instanceof Error) {
msg += '\n-------\nCaused by: ' + cause.stack + '\n-------\n';
}
this.message = msg;
}
export class IllegalArgumentException extends ExtendableError {
constructor(message = 'IllegalArgumentException') {
super(message);
function messageForDateTimeParseException(message, text = '', index = 0, cause = null) {
let msg = message || this.name;
msg += ': ' + text + ', at index: ' + index;
if (cause !== null && cause instanceof Error) {
msg += '\n-------\nCaused by: ' + cause.stack + '\n-------\n';
}
this.message = msg;
}
export class IllegalStateException extends ExtendableError {
constructor(message = 'IllegalStateException') {
super(message);
}
}
export class NullPointerException extends ExtendableError {
constructor(message = 'NullPointerException') {
super(message);
}
}

@@ -350,6 +350,6 @@ /*

if (resolverStyle === ResolverStyle.SMART &&
hod.longValue() === 24 &&
(moh == null || moh.longValue() === 0) &&
(som == null || som.longValue() === 0) &&
(nos == null || nos.longValue() === 0)) {
hod === 24 &&
(moh == null || moh === 0) &&
(som == null || som === 0) &&
(nos == null || nos === 0)) {
hod = 0;

@@ -356,0 +356,0 @@ this.excessDays = Period.ofDays(1);

@@ -45,3 +45,3 @@ /**

*/
constructor(printerParser, locale, decimalStyle, resolverStyle, resolverFields, chrono, zone) {
constructor(printerParser, locale, decimalStyle, resolverStyle, resolverFields, chrono=IsoChronology.INSTANCE, zone) {
assert(printerParser != null);

@@ -48,0 +48,0 @@ assert(decimalStyle != null);

@@ -0,1 +1,7 @@

/*
* @copyright (c) 2016, Philipp Thuerwaechter & Pattrick Hueper
* @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos
* @license BSD-3-Clause (see LICENSE in the root directory of this source tree)
*/
import {DateTimeException} from '../errors';

@@ -2,0 +8,0 @@

@@ -0,1 +1,9 @@

/*
* @copyright (c) 2016, Philipp Thuerwaechter & Pattrick Hueper
* @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos
* @license BSD-3-Clause (see LICENSE in the root directory of this source tree)
*/
import {Enum} from '../Enum';
/**

@@ -48,4 +56,2 @@ * Enumeration of different ways to resolve dates and times.

*/
import {Enum} from '../Enum';
export class ResolverStyle extends Enum {}

@@ -52,0 +58,0 @@

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

export { LocalDateTime } from './LocalDateTime';
export { MathUtil } from './MathUtil';
// export { MathUtil } from './MathUtil'; what for export MathUtil ?
export { Month } from './Month';

@@ -23,3 +23,8 @@ export { Period } from './Period';

export {TemporalAdjusters} from './temporal/TemporalAdjusters';
export {TemporalQueries} from './temporal/TemporalQueries';
export {DateTimeFormatter} from './format/DateTimeFormatter';
export {DateTimeFormatterBuilder} from './format/DateTimeFormatterBuilder';
export {ResolverStyle} from './format/ResolverStyle';
import './_init';
/*
* @copyright (c) 2016, Philipp Thuerwaechter & Pattrick Hueper
* @copyright (c) 2016, Philipp Thuerwaechter & Pattrick Hueper
* @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos

@@ -4,0 +4,0 @@ * @license BSD-3-Clause (see LICENSE in the root directory of this source tree)

/*
* @copyright (c) 2016, Philipp Thuerwaechter & Pattrick Hueper
* @copyright (c) 2016, Philipp Thuerwaechter & Pattrick Hueper
* @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos
* @license BSD-3-Clause (see LICENSE in the root directory of this source tree)
*/
import {abstractMethodFail} from '../assert';
/**

@@ -83,5 +86,5 @@ * Strategy for adjusting a temporal object.

adjustInto(temporal){
throw Error('abstract');
abstractMethodFail('adjustInto');
}
}

@@ -7,4 +7,158 @@ /*

import {abstractMethodFail} from '../assert';
/**
* Framework-level interface defining an amount of time, such as
* "6 hours", "8 days" or "2 years and 3 months".
* <p>
* This is the base interface type for amounts of time.
* An amount is distinct from a date or time-of-day in that it is not tied
* to any specific point on the time-line.
* <p>
* The amount can be thought of as a {@code Map} of {@link TemporalUnit} to
* {@code long}, exposed via {@link #getUnits()} and {@link #get(TemporalUnit)}.
* A simple case might have a single unit-value pair, such as "6 hours".
* A more complex case may have multiple unit-value pairs, such as
* "7 years, 3 months and 5 days".
* <p>
* There are two common implementations.
* {@link Period} is a date-based implementation, storing years, months and days.
* {@link Duration} is a time-based implementation, storing seconds and nanoseconds,
* but providing some access using other duration based units such as minutes,
* hours and fixed 24-hour days.
* <p>
* This interface is a framework-level interface that should not be widely
* used in application code. Instead, applications should create and pass
* around instances of concrete types, such as {@code Period} and {@code Duration}.
*
* @interface
*/
export class TemporalAmount{
/**
* Returns the value of the requested unit.
* The units returned from {@link #getUnits()} uniquely define the
* value of the {@code TemporalAmount}. A value must be returned
* for each unit listed in {@code getUnits}.
*
* @implSpec
* Implementations may declare support for units not listed by {@link #getUnits()}.
* Typically, the implementation would define additional units
* as conversions for the convenience of developers.
*
* @param {TemporalUnit} unit - the {@code TemporalUnit} for which to return the value
* @return {number} the long value of the unit
* @throws DateTimeException if a value for the unit cannot be obtained
* @throws UnsupportedTemporalTypeException if the {@code unit} is not supported
*/
get(unit){
abstractMethodFail('adjustInto');
}
/**
* Returns the list of units uniquely defining the value of this TemporalAmount.
* The list of {@code TemporalUnits} is defined by the implementation class.
* The list is a snapshot of the units at the time {@code getUnits}
* is called and is not mutable.
* The units are ordered from longest duration to the shortest duration
* of the unit.
*
* @implSpec
* The list of units completely and uniquely represents the
* state of the object without omissions, overlaps or duplication.
* The units are in order from longest duration to shortest.
*
* @return {TemporalUnit[]} the List of {@code TemporalUnits}; not null
*/
getUnits(){
abstractMethodFail('adjustInto');
}
/**
* Adds to the specified temporal object.
* <p>
* Adds the amount to the specified temporal object using the logic
* encapsulated in the implementing class.
* <p>
* There are two equivalent ways of using this method.
* The first is to invoke this method directly.
* The second is to use {@link Temporal#plus(TemporalAmount)}:
* <pre>
* // These two lines are equivalent, but the second approach is recommended
* dateTime = amount.addTo(dateTime);
* dateTime = dateTime.plus(adder);
* </pre>
* It is recommended to use the second approach, {@code plus(TemporalAmount)},
* as it is a lot clearer to read in code.
*
* @implSpec
* The implementation must take the input object and add to it.
* The implementation defines the logic of the addition and is responsible for
* documenting that logic. It may use any method on {@code Temporal} to
* query the temporal object and perform the addition.
* The returned object must have the same observable type as the input object
* <p>
* The input object must not be altered.
* Instead, an adjusted copy of the original must be returned.
* This provides equivalent, safe behavior for immutable and mutable temporal objects.
* <p>
* The input temporal object may be in a calendar system other than ISO.
* Implementations may choose to document compatibility with other calendar systems,
* or reject non-ISO temporal objects by {@link TemporalQueries#chronology() querying the chronology}.
* <p>
* This method may be called from multiple threads in parallel.
* It must be thread-safe when invoked.
*
* @param {Temporal} temporal - the temporal object to add the amount to, not null
* @return {Temporal} an object of the same observable type with the addition made, not null
* @throws DateTimeException if unable to add
* @throws ArithmeticException if numeric overflow occurs
*/
addTo(temporal){
abstractMethodFail('adjustInto');
}
/**
* Subtracts this object from the specified temporal object.
* <p>
* Subtracts the amount from the specified temporal object using the logic
* encapsulated in the implementing class.
* <p>
* There are two equivalent ways of using this method.
* The first is to invoke this method directly.
* The second is to use {@link Temporal#minus(TemporalAmount)}:
* <pre>
* // these two lines are equivalent, but the second approach is recommended
* dateTime = amount.subtractFrom(dateTime);
* dateTime = dateTime.minus(amount);
* </pre>
* It is recommended to use the second approach, {@code minus(TemporalAmount)},
* as it is a lot clearer to read in code.
*
* @implSpec
* The implementation must take the input object and subtract from it.
* The implementation defines the logic of the subtraction and is responsible for
* documenting that logic. It may use any method on {@code Temporal} to
* query the temporal object and perform the subtraction.
* The returned object must have the same observable type as the input object
* <p>
* The input object must not be altered.
* Instead, an adjusted copy of the original must be returned.
* This provides equivalent, safe behavior for immutable and mutable temporal objects.
* <p>
* The input temporal object may be in a calendar system other than ISO.
* Implementations may choose to document compatibility with other calendar systems,
* or reject non-ISO temporal objects by {@link TemporalQueries#chronology() querying the chronology}.
* <p>
* This method may be called from multiple threads in parallel.
* It must be thread-safe when invoked.
*
* @param {Temporal} temporal - the temporal object to subtract the amount from, not null
* @return {Temporal} an object of the same observable type with the subtraction made, not null
* @throws DateTimeException if unable to subtract
* @throws ArithmeticException if numeric overflow occurs
*/
subtractFrom(temporal){
abstractMethodFail('adjustInto');
}
}

@@ -8,3 +8,15 @@ /**

/**
* see {@link ChronoField} for a description
* A field of date-time, such as month-of-year or hour-of-minute.
* <p>
* Date and time is expressed using fields which partition the time-line into something
* meaningful for humans. Implementations of this interface represent those fields.
* <p>
* The most commonly used units are defined in {@link ChronoField}.
* Further fields are supplied in {@link IsoFields}, {@link WeekFields} and {@link JulianFields}.
* Fields can also be written by application code by implementing this interface.
* <p>
* The field works using double dispatch. Client code calls methods on a date-time like
* {@code LocalDateTime} which check if the field is a {@code ChronoField}.
* If it is, then the date-time must handle it.
* Otherwise, the method call is re-dispatched to the matching method in this interface.
*

@@ -11,0 +23,0 @@ * @interface

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

import {abstractMethodFail} from '../assert';
import {Enum} from '../Enum';
/**

@@ -83,3 +87,3 @@ * Strategy for querying a temporal object.

queryFrom(temporal){
throw new Error('abstract class');
abstractMethodFail('queryFrom');
}

@@ -89,4 +93,2 @@

import {Enum} from '../Enum';
/**

@@ -93,0 +95,0 @@ * Factory to create something similar to the JSR-310 {TemporalQuery} interface, takes a function and returns a new TemporalQuery object that presents that function

@@ -8,3 +8,18 @@ /*

/**
* see {@link ChronoUnit} for a description
* A unit of date-time, such as Days or Hours.
* <p>
* Measurement of time is built on units, such as years, months, days, hours, minutes and seconds.
* Implementations of this interface represent those units.
* <p>
* An instance of this interface represents the unit itself, rather than an amount of the unit.
* See {@link Period} for a class that represents an amount in terms of the common units.
* <p>
* The most commonly used units are defined in {@link ChronoUnit}.
* Further units are supplied in {@link IsoFields}.
* Units can also be written by application code by implementing this interface.
* <p>
* The unit works using double dispatch. Client code calls methods on a date-time like
* {@code LocalDateTime} which check if the unit is a {@code ChronoUnit}.
* If it is, then the date-time must handle it.
* Otherwise, the method call is re-dispatched to the matching method in this interface.
*

@@ -11,0 +26,0 @@ * @interface

/*
/*
class ExtendableError extends Error {

@@ -54,2 +55,46 @@ constructor(message = '') {

console.log(e instanceof DateTimeException);
console.log(e.stack);
console.log(e.stack);
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}

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

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