luxon
Version:
Immutable date wrapper
1,334 lines (1,216 loc) • 69 kB
JavaScript
import Duration, { friendlyDuration } from './duration';
import Interval from './interval';
import Settings from './settings';
import Info from './info';
import Formatter from './impl/formatter';
import FixedOffsetZone from './zones/fixedOffsetZone';
import LocalZone from './zones/localZone';
import Locale from './impl/locale';
import {
isUndefined,
maybeArray,
isDate,
isNumber,
bestBy,
daysInMonth,
daysInYear,
isLeapYear,
weeksInWeekYear,
normalizeObject
} from './impl/util';
import { normalizeZone } from './impl/zoneUtil';
import diff from './impl/diff';
import { parseRFC2822Date, parseISODate, parseHTTPDate, parseSQL } from './impl/regexParser';
import { parseFromTokens, explainFromTokens } from './impl/tokenParser';
import {
gregorianToWeek,
weekToGregorian,
gregorianToOrdinal,
ordinalToGregorian,
hasInvalidGregorianData,
hasInvalidWeekData,
hasInvalidOrdinalData,
hasInvalidTimeData
} from './impl/conversions';
import * as Formats from './impl/formats';
import {
InvalidArgumentError,
ConflictingSpecificationError,
InvalidUnitError,
InvalidDateTimeError
} from './errors';
const INVALID = 'Invalid DateTime',
INVALID_INPUT = 'invalid input',
UNSUPPORTED_ZONE = 'unsupported zone',
UNPARSABLE = 'unparsable';
// we cache week data on the DT object and this intermediates the cache
function possiblyCachedWeekData(dt) {
if (dt.weekData === null) {
dt.weekData = gregorianToWeek(dt.c);
}
return dt.weekData;
}
// clone really means, "make a new object with these modifications". all "setters" really use this
// to create a new object while only changing some of the properties
function clone(inst, alts) {
const current = {
ts: inst.ts,
zone: inst.zone,
c: inst.c,
o: inst.o,
loc: inst.loc,
invalidReason: inst.invalidReason
};
return new DateTime(Object.assign({}, current, alts, { old: current }));
}
// find the right offset a given local time. The o input is our guess, which determines which
// offset we'll pick in ambiguous cases (e.g. there are two 3 AMs b/c Fallback DST)
function fixOffset(localTS, o, tz) {
// Our UTC time is just a guess because our offset is just a guess
let utcGuess = localTS - o * 60 * 1000;
// Test whether the zone matches the offset for this ts
const o2 = tz.offset(utcGuess);
// If so, offset didn't change and we're done
if (o === o2) {
return [utcGuess, o];
}
// If not, change the ts by the difference in the offset
utcGuess -= (o2 - o) * 60 * 1000;
// If that gives us the local time we want, we're done
const o3 = tz.offset(utcGuess);
if (o2 === o3) {
return [utcGuess, o2];
}
// If it's different, we're in a hole time. The offset has changed, but the we don't adjust the time
return [localTS - Math.min(o2, o3) * 60 * 1000, Math.max(o2, o3)];
}
// convert an epoch timestamp into a calendar object with the given offset
function tsToObj(ts, offset) {
ts += offset * 60 * 1000;
const d = new Date(ts);
return {
year: d.getUTCFullYear(),
month: d.getUTCMonth() + 1,
day: d.getUTCDate(),
hour: d.getUTCHours(),
minute: d.getUTCMinutes(),
second: d.getUTCSeconds(),
millisecond: d.getUTCMilliseconds()
};
}
// covert a calendar object to a local timestamp (epoch, but with the offset baked in)
function objToLocalTS(obj) {
let d = Date.UTC(
obj.year,
obj.month - 1,
obj.day,
obj.hour,
obj.minute,
obj.second,
obj.millisecond
);
// javascript is stupid and i hate it
if (obj.year < 100 && obj.year >= 0) {
d = new Date(d);
d.setUTCFullYear(obj.year);
}
return +d;
}
// convert a calendar object to a epoch timestamp
function objToTS(obj, offset, zone) {
return fixOffset(objToLocalTS(obj), offset, zone);
}
// create a new DT instance by adding a duration, adjusting for DSTs
function adjustTime(inst, dur) {
const oPre = inst.o,
year = inst.c.year + dur.years,
month = inst.c.month + dur.months + dur.quarters * 3,
c = Object.assign({}, inst.c, {
year,
month,
day: Math.min(inst.c.day, daysInMonth(year, month)) + dur.days + dur.weeks * 7
}),
millisToAdd = Duration.fromObject({
hours: dur.hours,
minutes: dur.minutes,
seconds: dur.seconds,
milliseconds: dur.milliseconds
}).as('milliseconds'),
localTS = objToLocalTS(c);
let [ts, o] = fixOffset(localTS, oPre, inst.zone);
if (millisToAdd !== 0) {
ts += millisToAdd;
// that could have changed the offset by going over a DST, but we want to keep the ts the same
o = inst.zone.offset(ts);
}
return { ts, o };
}
// helper useful in turning the results of parsing into real dates
// by handling the zone options
function parseDataToDateTime(parsed, parsedZone, opts) {
const { setZone, zone } = opts;
if (parsed && Object.keys(parsed).length !== 0) {
const interpretationZone = parsedZone || zone,
inst = DateTime.fromObject(
Object.assign(parsed, opts, {
zone: interpretationZone
})
);
return setZone ? inst : inst.setZone(zone);
} else {
return DateTime.invalid(UNPARSABLE);
}
}
// if you want to output a technical format (e.g. RFC 2822), this helper
// helps handle the details
function toTechFormat(dt, format) {
return dt.isValid
? Formatter.create(Locale.create('en-US'), {
allowZ: true,
forceSimple: true
}).formatDateTimeFromString(dt, format)
: null;
}
// technical time formats (e.g. the time part of ISO 8601), take some options
// and this commonizes their handling
function toTechTimeFormat(
dt,
{
suppressSeconds = false,
suppressMilliseconds = false,
includeOffset = true,
includeZone = false,
spaceZone = false
}
) {
let fmt = 'HH:mm';
if (!suppressSeconds || dt.second !== 0 || dt.millisecond !== 0) {
fmt += ':ss';
if (!suppressMilliseconds || dt.millisecond !== 0) {
fmt += '.SSS';
}
}
if ((includeZone || includeOffset) && spaceZone) {
fmt += ' ';
}
if (includeZone) {
fmt += 'z';
} else if (includeOffset) {
fmt += 'ZZ';
}
return toTechFormat(dt, fmt);
}
// defaults for unspecified units in the supported calendars
const defaultUnitValues = {
month: 1,
day: 1,
hour: 0,
minute: 0,
second: 0,
millisecond: 0
},
defaultWeekUnitValues = {
weekNumber: 1,
weekday: 1,
hour: 0,
minute: 0,
second: 0,
millisecond: 0
},
defaultOrdinalUnitValues = {
ordinal: 1,
hour: 0,
minute: 0,
second: 0,
millisecond: 0
};
// Units in the supported calendars, sorted by bigness
const orderedUnits = ['year', 'month', 'day', 'hour', 'minute', 'second', 'millisecond'],
orderedWeekUnits = [
'weekYear',
'weekNumber',
'weekday',
'hour',
'minute',
'second',
'millisecond'
],
orderedOrdinalUnits = ['year', 'ordinal', 'hour', 'minute', 'second', 'millisecond'];
// standardize case and plurality in units
function normalizeUnit(unit, ignoreUnknown = false) {
const normalized = {
year: 'year',
years: 'year',
month: 'month',
months: 'month',
day: 'day',
days: 'day',
hour: 'hour',
hours: 'hour',
minute: 'minute',
minutes: 'minute',
second: 'second',
seconds: 'second',
millisecond: 'millisecond',
milliseconds: 'millisecond',
weekday: 'weekday',
weekdays: 'weekday',
weeknumber: 'weekNumber',
weeksnumber: 'weekNumber',
weeknumbers: 'weekNumber',
weekyear: 'weekYear',
weekyears: 'weekYear',
ordinal: 'ordinal'
}[unit ? unit.toLowerCase() : unit];
if (!ignoreUnknown && !normalized) throw new InvalidUnitError(unit);
return normalized;
}
// this is a dumbed down version of fromObject() that runs about 60% faster
// but doesn't do any validation, makes a bunch of assumptions about what units
// are present, and so on.
function quickDT(obj, zone) {
// assume we have the higher-order units
for (const u of orderedUnits) {
if (isUndefined(obj[u])) {
obj[u] = defaultUnitValues[u];
}
}
const invalidReason = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj);
if (invalidReason) {
return DateTime.invalid(invalidReason);
}
const tsNow = Settings.now(),
offsetProvis = zone.offset(tsNow),
[ts, o] = objToTS(obj, offsetProvis, zone);
return new DateTime({
ts,
zone,
o
});
}
/**
* A DateTime is an immutable data structure representing a specific date and time and accompanying methods. It contains class and instance methods for creating, parsing, interrogating, transforming, and formatting them.
*
* A DateTime comprises of:
* * A timestamp. Each DateTime instance refers to a specific millisecond of the Unix epoch.
* * A time zone. Each instance is considered in the context of a specific zone (by default the local system's zone).
* * Configuration properties that effect how output strings are formatted, such as `locale`, `numberingSystem`, and `outputCalendar`.
*
* Here is a brief overview of the most commonly used functionality it provides:
*
* * **Creation**: To create a DateTime from its components, use one of its factory class methods: {@link local}, {@link utc}, and (most flexibly) {@link fromObject}. To create one from a standard string format, use {@link fromISO}, {@link fromHTTP}, and {@link fromRFC2822}. To create one from a custom string format, use {@link fromFormat}. To create one from a native JS date, use {@link fromJSDate}.
* * **Gregorian calendar and time**: To examine the Gregorian properties of a DateTime individually (i.e as opposed to collectively through {@link toObject}), use the {@link year}, {@link month},
* {@link day}, {@link hour}, {@link minute}, {@link second}, {@link millisecond} accessors.
* * **Week calendar**: For ISO week calendar attributes, see the {@link weekYear}, {@link weekNumber}, and {@link weekday} accessors.
* * **Configuration** See the {@link locale} and {@link numberingSystem} accessors.
* * **Transformation**: To transform the DateTime into other DateTimes, use {@link set}, {@link reconfigure}, {@link setZone}, {@link setLocale}, {@link plus}, {@link minus}, {@link endOf}, {@link startOf}, {@link toUTC}, and {@link toLocal}.
* * **Output**: To convert the DateTime to other representations, use the {@link toJSON}, {@link toISO}, {@link toHTTP}, {@link toObject}, {@link toRFC2822}, {@link toString}, {@link toLocaleString}, {@link toFormat}, {@link valueOf} and {@link toJSDate}.
*
* There's plenty others documented below. In addition, for more information on subtler topics like internationalization, time zones, alternative calendars, validity, and so on, see the external documentation.
*/
export default class DateTime {
/**
* @access private
*/
constructor(config) {
const zone = config.zone || Settings.defaultZone,
invalidReason =
config.invalidReason ||
(Number.isNaN(config.ts) ? INVALID_INPUT : null) ||
(!zone.isValid ? UNSUPPORTED_ZONE : null);
/**
* @access private
*/
this.ts = isUndefined(config.ts) ? Settings.now() : config.ts;
let c = null,
o = null;
if (!invalidReason) {
const unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone);
c = unchanged ? config.old.c : tsToObj(this.ts, zone.offset(this.ts));
o = unchanged ? config.old.o : zone.offset(this.ts);
}
/**
* @access private
*/
this.zone = zone;
/**
* @access private
*/
this.loc = config.loc || Locale.create();
/**
* @access private
*/
this.invalid = invalidReason;
/**
* @access private
*/
this.weekData = null;
/**
* @access private
*/
this.c = c;
/**
* @access private
*/
this.o = o;
}
// CONSTRUCT
/**
* Create a local DateTime
* @param {number} year - The calendar year. If omitted (as in, call `local()` with no arguments), the current time will be used
* @param {number} [month=1] - The month, 1-indexed
* @param {number} [day=1] - The day of the month
* @param {number} [hour=0] - The hour of the day, in 24-hour time
* @param {number} [minute=0] - The minute of the hour, i.e. a number between 0 and 59
* @param {number} [second=0] - The second of the minute, i.e. a number between 0 and 59
* @param {number} [millisecond=0] - The millisecond of the second, i.e. a number between 0 and 999
* @example DateTime.local() //~> now
* @example DateTime.local(2017) //~> 2017-01-01T00:00:00
* @example DateTime.local(2017, 3) //~> 2017-03-01T00:00:00
* @example DateTime.local(2017, 3, 12) //~> 2017-03-12T00:00:00
* @example DateTime.local(2017, 3, 12, 5) //~> 2017-03-12T05:00:00
* @example DateTime.local(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00
* @example DateTime.local(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10
* @example DateTime.local(2017, 3, 12, 5, 45, 10, 765) //~> 2017-03-12T05:45:10.765
* @return {DateTime}
*/
static local(year, month, day, hour, minute, second, millisecond) {
if (isUndefined(year)) {
return new DateTime({ ts: Settings.now() });
} else {
return quickDT(
{
year,
month,
day,
hour,
minute,
second,
millisecond
},
Settings.defaultZone
);
}
}
/**
* Create a DateTime in UTC
* @param {number} year - The calendar year. If omitted (as in, call `utc()` with no arguments), the current time will be used
* @param {number} [month=1] - The month, 1-indexed
* @param {number} [day=1] - The day of the month
* @param {number} [hour=0] - The hour of the day, in 24-hour time
* @param {number} [minute=0] - The minute of the hour, i.e. a number between 0 and 59
* @param {number} [second=0] - The second of the minute, i.e. a number between 0 and 59
* @param {number} [millisecond=0] - The millisecond of the second, i.e. a number between 0 and 999
* @example DateTime.utc() //~> now
* @example DateTime.utc(2017) //~> 2017-01-01T00:00:00Z
* @example DateTime.utc(2017, 3) //~> 2017-03-01T00:00:00Z
* @example DateTime.utc(2017, 3, 12) //~> 2017-03-12T00:00:00Z
* @example DateTime.utc(2017, 3, 12, 5) //~> 2017-03-12T05:00:00Z
* @example DateTime.utc(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00Z
* @example DateTime.utc(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10Z
* @example DateTime.utc(2017, 3, 12, 5, 45, 10, 765) //~> 2017-03-12T05:45:10.765Z
* @return {DateTime}
*/
static utc(year, month, day, hour, minute, second, millisecond) {
if (isUndefined(year)) {
return new DateTime({
ts: Settings.now(),
zone: FixedOffsetZone.utcInstance
});
} else {
return quickDT(
{
year,
month,
day,
hour,
minute,
second,
millisecond
},
FixedOffsetZone.utcInstance
);
}
}
/**
* Create a DateTime from a Javascript Date object. Uses the default zone.
* @param {Date} date - a Javascript Date object
* @param {Object} options - configuration options for the DateTime
* @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
* @return {DateTime}
*/
static fromJSDate(date, options = {}) {
return new DateTime({
ts: isDate(date) ? date.valueOf() : NaN,
zone: normalizeZone(options.zone, Settings.defaultZone),
loc: Locale.fromObject(options)
});
}
/**
* Create a DateTime from a number of milliseconds since the epoch (i.e. since 1 January 1970 00:00:00 UTC). Uses the default zone.
* @param {number} milliseconds - a number of milliseconds since 1970 UTC
* @param {Object} options - configuration options for the DateTime
* @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
* @param {string} [options.locale] - a locale to set on the resulting DateTime instance
* @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance
* @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance
* @return {DateTime}
*/
static fromMillis(milliseconds, options = {}) {
return new DateTime({
ts: milliseconds,
zone: normalizeZone(options.zone, Settings.defaultZone),
loc: Locale.fromObject(options)
});
}
/**
* Create a DateTime from a Javascript object with keys like 'year' and 'hour' with reasonable defaults.
* @param {Object} obj - the object to create the DateTime from
* @param {number} obj.year - a year, such as 1987
* @param {number} obj.month - a month, 1-12
* @param {number} obj.day - a day of the month, 1-31, depending on the month
* @param {number} obj.ordinal - day of the year, 1-365 or 366
* @param {number} obj.weekYear - an ISO week year
* @param {number} obj.weekNumber - an ISO week number, between 1 and 52 or 53, depending on the year
* @param {number} obj.weekday - an ISO weekday, 1-7, where 1 is Monday and 7 is Sunday
* @param {number} obj.hour - hour of the day, 0-23
* @param {number} obj.minute - minute of the hour, 0-59
* @param {number} obj.second - second of the minute, 0-59
* @param {number} obj.millisecond - millisecond of the second, 0-999
* @param {string|Zone} [obj.zone='local'] - interpret the numbers in the context of a particular zone. Can take any value taken as the first argument to setZone()
* @param {string} [obj.locale='en-US'] - a locale to set on the resulting DateTime instance
* @param {string} obj.outputCalendar - the output calendar to set on the resulting DateTime instance
* @param {string} obj.numberingSystem - the numbering system to set on the resulting DateTime instance
* @example DateTime.fromObject({ year: 1982, month: 5, day: 25}).toISODate() //=> '1982-05-25'
* @example DateTime.fromObject({ year: 1982 }).toISODate() //=> '1982-01-01T00'
* @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }) //~> today at 10:26:06
* @example DateTime.fromObject({ hour: 10, minute: 26, second: 6, zone: 'utc' }),
* @example DateTime.fromObject({ hour: 10, minute: 26, second: 6, zone: 'local' })
* @example DateTime.fromObject({ hour: 10, minute: 26, second: 6, zone: 'America/New_York' })
* @example DateTime.fromObject({ weekYear: 2016, weekNumber: 2, weekday: 3 }).toISODate() //=> '2016-01-13'
* @return {DateTime}
*/
static fromObject(obj) {
const zoneToUse = normalizeZone(obj.zone, Settings.defaultZone);
if (!zoneToUse.isValid) {
return DateTime.invalid(UNSUPPORTED_ZONE);
}
const tsNow = Settings.now(),
offsetProvis = zoneToUse.offset(tsNow),
normalized = normalizeObject(obj, normalizeUnit, true),
containsOrdinal = !isUndefined(normalized.ordinal),
containsGregorYear = !isUndefined(normalized.year),
containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day),
containsGregor = containsGregorYear || containsGregorMD,
definiteWeekDef = normalized.weekYear || normalized.weekNumber,
loc = Locale.fromObject(obj);
// cases:
// just a weekday -> this week's instance of that weekday, no worries
// (gregorian data or ordinal) + (weekYear or weekNumber) -> error
// (gregorian month or day) + ordinal -> error
// otherwise just use weeks or ordinals or gregorian, depending on what's specified
if ((containsGregor || containsOrdinal) && definiteWeekDef) {
throw new ConflictingSpecificationError(
"Can't mix weekYear/weekNumber units with year/month/day or ordinals"
);
}
if (containsGregorMD && containsOrdinal) {
throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");
}
const useWeekData = definiteWeekDef || (normalized.weekday && !containsGregor);
// configure ourselves to deal with gregorian dates or week stuff
let units,
defaultValues,
objNow = tsToObj(tsNow, offsetProvis);
if (useWeekData) {
units = orderedWeekUnits;
defaultValues = defaultWeekUnitValues;
objNow = gregorianToWeek(objNow);
} else if (containsOrdinal) {
units = orderedOrdinalUnits;
defaultValues = defaultOrdinalUnitValues;
objNow = gregorianToOrdinal(objNow);
} else {
units = orderedUnits;
defaultValues = defaultUnitValues;
}
// set default values for missing stuff
let foundFirst = false;
for (const u of units) {
const v = normalized[u];
if (!isUndefined(v)) {
foundFirst = true;
} else if (foundFirst) {
normalized[u] = defaultValues[u];
} else {
normalized[u] = objNow[u];
}
}
// make sure the values we have are in range
const higherOrderInvalid = useWeekData
? hasInvalidWeekData(normalized)
: containsOrdinal ? hasInvalidOrdinalData(normalized) : hasInvalidGregorianData(normalized),
invalidReason = higherOrderInvalid || hasInvalidTimeData(normalized);
if (invalidReason) {
return DateTime.invalid(invalidReason);
}
// compute the actual time
const gregorian = useWeekData
? weekToGregorian(normalized)
: containsOrdinal ? ordinalToGregorian(normalized) : normalized,
[tsFinal, offsetFinal] = objToTS(gregorian, offsetProvis, zoneToUse),
inst = new DateTime({
ts: tsFinal,
zone: zoneToUse,
o: offsetFinal,
loc
});
// gregorian data + weekday serves only to validate
if (normalized.weekday && containsGregor && obj.weekday !== inst.weekday) {
return DateTime.invalid('mismatched weekday');
}
return inst;
}
/**
* Create a DateTime from an ISO 8601 string
* @param {string} text - the ISO string
* @param {Object} opts - options to affect the creation
* @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the time to this zone
* @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one
* @param {string} [opts.locale='en-US'] - a locale to set on the resulting DateTime instance
* @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
* @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
* @example DateTime.fromISO('2016-05-25T09:08:34.123')
* @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00')
* @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00', {setZone: true})
* @example DateTime.fromISO('2016-05-25T09:08:34.123', {zone: 'utc'})
* @example DateTime.fromISO('2016-W05-4')
* @return {DateTime}
*/
static fromISO(text, opts = {}) {
const [vals, parsedZone] = parseISODate(text);
return parseDataToDateTime(vals, parsedZone, opts);
}
/**
* Create a DateTime from an RFC 2822 string
* @param {string} text - the RFC 2822 string
* @param {Object} opts - options to affect the creation
* @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since the offset is always specified in the string itself, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.
* @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one
* @param {string} [opts.locale='en-US'] - a locale to set on the resulting DateTime instance
* @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
* @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
* @example DateTime.fromRFC2822('25 Nov 2016 13:23:12 GMT')
* @example DateTime.fromRFC2822('Tue, 25 Nov 2016 13:23:12 +0600')
* @example DateTime.fromRFC2822('25 Nov 2016 13:23 Z')
* @return {DateTime}
*/
static fromRFC2822(text, opts = {}) {
const [vals, parsedZone] = parseRFC2822Date(text);
return parseDataToDateTime(vals, parsedZone, opts);
}
/**
* Create a DateTime from an HTTP header date
* @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
* @param {string} text - the HTTP header date
* @param {Object} options - options to affect the creation
* @param {string|Zone} [options.zone='local'] - convert the time to this zone. Since HTTP dates are always in UTC, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.
* @param {boolean} [options.setZone=false] - override the zone with the fixed-offset zone specified in the string. For HTTP dates, this is always UTC, so this option is equivalent to setting the `zone` option to 'utc', but this option is included for consistency with similar methods.
* @param {string} [options.locale='en-US'] - a locale to set on the resulting DateTime instance
* @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance
* @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance
* @example DateTime.fromHTTP('Sun, 06 Nov 1994 08:49:37 GMT')
* @example DateTime.fromHTTP('Sunday, 06-Nov-94 08:49:37 GMT')
* @example DateTime.fromHTTP('Sun Nov 6 08:49:37 1994')
* @return {DateTime}
*/
static fromHTTP(text, options = {}) {
const [vals, parsedZone] = parseHTTPDate(text);
return parseDataToDateTime(vals, parsedZone, options);
}
/**
* Create a DateTime from an input string and format string
* Defaults to en-US if no locale has been specified, regardless of the system's locale
* @param {string} text - the string to parse
* @param {string} fmt - the format the string is expected to be in (see description)
* @param {Object} options - options to affect the creation
* @param {string|Zone} [options.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone
* @param {boolean} [options.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one
* @param {string} [options.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale
* @param {string} options.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system
* @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance
* @return {DateTime}
*/
static fromFormat(text, fmt, options = {}) {
if (isUndefined(text) || isUndefined(fmt)) {
throw new InvalidArgumentError('fromFormat requires an input string and a format');
}
const { locale = null, numberingSystem = null } = options,
localeToUse = Locale.fromOpts({ locale, numberingSystem, defaultToEN: true }),
[vals, parsedZone, invalidReason] = parseFromTokens(localeToUse, text, fmt);
if (invalidReason) {
return DateTime.invalid(invalidReason);
} else {
return parseDataToDateTime(vals, parsedZone, options);
}
}
/**
* @deprecated use fromFormat instead
*/
static fromString(text, fmt, opts = {}) {
return DateTime.fromFormat(text, fmt, opts);
}
/**
* Create a DateTime from a SQL date, time, or datetime
* Defaults to en-US if no locale has been specified, regardless of the system's locale
* @param {string} text - the string to parse
* @param {Object} options - options to affect the creation
* @param {string|Zone} [options.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone
* @param {boolean} [options.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one
* @param {string} [options.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale
* @param {string} options.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system
* @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance
* @example DateTime.fromSQL('2017-05-15')
* @example DateTime.fromSQL('2017-05-15 09:12:34')
* @example DateTime.fromSQL('2017-05-15 09:12:34.342')
* @example DateTime.fromSQL('2017-05-15 09:12:34.342+06:00')
* @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles')
* @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles', { setZone: true })
* @example DateTime.fromSQL('2017-05-15 09:12:34.342', { zone: 'America/Los_Angeles' })
* @example DateTime.fromSQL('09:12:34.342')
* @return {DateTime}
*/
static fromSQL(text, options = {}) {
const [vals, parsedZone] = parseSQL(text);
return parseDataToDateTime(vals, parsedZone, options);
}
/**
* Create an invalid DateTime.
* @return {DateTime}
*/
static invalid(reason) {
if (!reason) {
throw new InvalidArgumentError('need to specify a reason the DateTime is invalid');
}
if (Settings.throwOnInvalid) {
throw new InvalidDateTimeError(reason);
} else {
return new DateTime({ invalidReason: reason });
}
}
// INFO
/**
* Get the value of unit.
* @param {string} unit - a unit such as 'minute' or 'day'
* @example DateTime.local(2017, 7, 4).get('month'); //=> 7
* @example DateTime.local(2017, 7, 4).get('day'); //=> 4
* @return {number}
*/
get(unit) {
return this[unit];
}
/**
* Returns whether the DateTime is valid. Invalid DateTimes occur when:
* * The DateTime was created from invalid calendar information, such as the 13th month or February 30
* * The DateTime was created by an operation on another invalid date
* @type {boolean}
*/
get isValid() {
return this.invalidReason === null;
}
/**
* Returns an explanation of why this DateTime became invalid, or null if the DateTime is valid
* @type {string}
*/
get invalidReason() {
return this.invalid;
}
/**
* Get the locale of a DateTime, such 'en-GB'. The locale is used when formatting the DateTime
*
* @type {string}
*/
get locale() {
return this.isValid ? this.loc.locale : null;
}
/**
* Get the numbering system of a DateTime, such 'beng'. The numbering system is used when formatting the DateTime
*
* @type {string}
*/
get numberingSystem() {
return this.isValid ? this.loc.numberingSystem : null;
}
/**
* Get the output calendar of a DateTime, such 'islamic'. The output calendar is used when formatting the DateTime
*
* @type {string}
*/
get outputCalendar() {
return this.isValid ? this.loc.outputCalendar : null;
}
/**
* Get the name of the time zone.
* @type {string}
*/
get zoneName() {
return this.isValid ? this.zone.name : null;
}
/**
* Get the year
* @example DateTime.local(2017, 5, 25).year //=> 2017
* @type {number}
*/
get year() {
return this.isValid ? this.c.year : NaN;
}
/**
* Get the quarter
* @example DateTime.local(2017, 5, 25).quarter //=> 2
* @type {number}
*/
get quarter() {
return this.isValid ? Math.ceil(this.c.month / 3) : NaN;
}
/**
* Get the month (1-12).
* @example DateTime.local(2017, 5, 25).month //=> 5
* @type {number}
*/
get month() {
return this.isValid ? this.c.month : NaN;
}
/**
* Get the day of the month (1-30ish).
* @example DateTime.local(2017, 5, 25).day //=> 25
* @type {number}
*/
get day() {
return this.isValid ? this.c.day : NaN;
}
/**
* Get the hour of the day (0-23).
* @example DateTime.local(2017, 5, 25, 9).hour //=> 9
* @type {number}
*/
get hour() {
return this.isValid ? this.c.hour : NaN;
}
/**
* Get the minute of the hour (0-59).
* @example DateTime.local(2017, 5, 25, 9, 30).minute //=> 30
* @type {number}
*/
get minute() {
return this.isValid ? this.c.minute : NaN;
}
/**
* Get the second of the minute (0-59).
* @example DateTime.local(2017, 5, 25, 9, 30, 52).second //=> 52
* @type {number}
*/
get second() {
return this.isValid ? this.c.second : NaN;
}
/**
* Get the millisecond of the second (0-999).
* @example DateTime.local(2017, 5, 25, 9, 30, 52, 654).millisecond //=> 654
* @type {number}
*/
get millisecond() {
return this.isValid ? this.c.millisecond : NaN;
}
/**
* Get the week year
* @see https://en.wikipedia.org/wiki/ISO_week_date
* @example DateTime.local(2014, 11, 31).weekYear //=> 2015
* @type {number}
*/
get weekYear() {
return this.isValid ? possiblyCachedWeekData(this).weekYear : NaN;
}
/**
* Get the week number of the week year (1-52ish).
* @see https://en.wikipedia.org/wiki/ISO_week_date
* @example DateTime.local(2017, 5, 25).weekNumber //=> 21
* @type {number}
*/
get weekNumber() {
return this.isValid ? possiblyCachedWeekData(this).weekNumber : NaN;
}
/**
* Get the day of the week.
* 1 is Monday and 7 is Sunday
* @see https://en.wikipedia.org/wiki/ISO_week_date
* @example DateTime.local(2014, 11, 31).weekday //=> 4
* @type {number}
*/
get weekday() {
return this.isValid ? possiblyCachedWeekData(this).weekday : NaN;
}
/**
* Get the ordinal (i.e. the day of the year)
* @example DateTime.local(2017, 5, 25).ordinal //=> 145
* @type {number|DateTime}
*/
get ordinal() {
return this.isValid ? gregorianToOrdinal(this.c).ordinal : NaN;
}
/**
* Get the human readable short month name, such as 'Oct'.
* Defaults to the system's locale if no locale has been specified
* @example DateTime.local(2017, 10, 30).monthShort //=> Oct
* @type {string}
*/
get monthShort() {
return this.isValid ? Info.months('short', { locale: this.locale })[this.month - 1] : null;
}
/**
* Get the human readable long month name, such as 'October'.
* Defaults to the system's locale if no locale has been specified
* @example DateTime.local(2017, 10, 30).monthLong //=> October
* @type {string}
*/
get monthLong() {
return this.isValid ? Info.months('long', { locale: this.locale })[this.month - 1] : null;
}
/**
* Get the human readable short weekday, such as 'Mon'.
* Defaults to the system's locale if no locale has been specified
* @example DateTime.local(2017, 10, 30).weekdayShort //=> Mon
* @type {string}
*/
get weekdayShort() {
return this.isValid ? Info.weekdays('short', { locale: this.locale })[this.weekday - 1] : null;
}
/**
* Get the human readable long weekday, such as 'Monday'.
* Defaults to the system's locale if no locale has been specified
* @example DateTime.local(2017, 10, 30).weekdayLong //=> Monday
* @type {string}
*/
get weekdayLong() {
return this.isValid ? Info.weekdays('long', { locale: this.locale })[this.weekday - 1] : null;
}
/**
* Get the UTC offset of this DateTime in minutes
* @example DateTime.local().offset //=> -240
* @example DateTime.utc().offset //=> 0
* @type {number}
*/
get offset() {
return this.isValid ? this.zone.offset(this.ts) : NaN;
}
/**
* Get the short human name for the zone's current offset, for example "EST" or "EDT".
* Defaults to the system's locale if no locale has been specified
* @type {string}
*/
get offsetNameShort() {
if (this.isValid) {
return this.zone.offsetName(this.ts, {
format: 'short',
locale: this.locale
});
} else {
return null;
}
}
/**
* Get the long human name for the zone's current offset, for example "Eastern Standard Time" or "Eastern Daylight Time".
* Defaults to the system's locale if no locale has been specified
* @type {string}
*/
get offsetNameLong() {
if (this.isValid) {
return this.zone.offsetName(this.ts, {
format: 'long',
locale: this.locale
});
} else {
return null;
}
}
/**
* Get whether this zone's offset ever changes, as in a DST.
* @type {boolean}
*/
get isOffsetFixed() {
return this.isValid ? this.zone.universal : null;
}
/**
* Get whether the DateTime is in a DST.
* @type {boolean}
*/
get isInDST() {
if (this.isOffsetFixed) {
return false;
} else {
return (
this.offset > this.set({ month: 1 }).offset || this.offset > this.set({ month: 5 }).offset
);
}
}
/**
* Returns true if this DateTime is in a leap year, false otherwise
* @example DateTime.local(2016).isInLeapYear //=> true
* @example DateTime.local(2013).isInLeapYear //=> false
* @type {boolean}
*/
get isInLeapYear() {
return isLeapYear(this.year);
}
/**
* Returns the number of days in this DateTime's month
* @example DateTime.local(2016, 2).daysInMonth //=> 29
* @example DateTime.local(2016, 3).daysInMonth //=> 31
* @type {number}
*/
get daysInMonth() {
return daysInMonth(this.year, this.month);
}
/**
* Returns the number of days in this DateTime's year
* @example DateTime.local(2016).daysInYear //=> 366
* @example DateTime.local(2013).daysInYear //=> 365
* @type {number}
*/
get daysInYear() {
return this.isValid ? daysInYear(this.year) : NaN;
}
/**
* Returns the number of weeks in this DateTime's year
* @see https://en.wikipedia.org/wiki/ISO_week_date
* @example DateTime.local(2004).weeksInWeekYear //=> 53
* @example DateTime.local(2013).weeksInWeekYear //=> 52
* @type {number}
*/
get weeksInWeekYear() {
return this.isValid ? weeksInWeekYear(this.weekYear) : NaN;
}
/**
* Returns the resolved Intl options for this DateTime.
* This is useful in understanding the behavior of formatting methods
* @param {Object} opts - the same options as toLocaleString
* @return {Object}
*/
resolvedLocaleOpts(opts = {}) {
const { locale, numberingSystem, calendar } = Formatter.create(
this.loc.clone(opts),
opts
).resolvedOptions(this);
return { locale, numberingSystem, outputCalendar: calendar };
}
// TRANSFORM
/**
* "Set" the DateTime's zone to UTC. Returns a newly-constructed DateTime.
*
* Equivalent to {@link setZone}('utc')
* @param {number} [offset=0] - optionally, an offset from UTC in minutes
* @param {Object} [opts={}] - options to pass to `setZone()`
* @return {DateTime}
*/
toUTC(offset = 0, opts = {}) {
return this.setZone(FixedOffsetZone.instance(offset), opts);
}
/**
* "Set" the DateTime's zone to the host's local zone. Returns a newly-constructed DateTime.
*
* Equivalent to `setZone('local')`
* @return {DateTime}
*/
toLocal() {
return this.setZone(new LocalZone());
}
/**
* "Set" the DateTime's zone to specified zone. Returns a newly-constructed DateTime.
*
* By default, the setter keeps the underlying time the same (as in, the same UTC timestamp), but the new instance will report different local times and consider DSTs when making computations, as with {@link plus}. You may wish to use {@link toLocal} and {@link toUTC} which provide simple convenience wrappers for commonly used zones.
* @param {string|Zone} [zone='local'] - a zone identifier. As a string, that can be any IANA zone supported by the host environment, or a fixed-offset name of the form 'utc+3', or the strings 'local' or 'utc'. You may also supply an instance of a {@link Zone} class.
* @param {Object} opts - options
* @param {boolean} [opts.keepLocalTime=false] - If true, adjust the underlying time so that the local time stays the same, but in the target zone. You should rarely need this.
* @return {DateTime}
*/
setZone(zone, { keepLocalTime = false, keepCalendarTime = false } = {}) {
zone = normalizeZone(zone, Settings.defaultZone);
if (zone.equals(this.zone)) {
return this;
} else if (!zone.isValid) {
return DateTime.invalid(UNSUPPORTED_ZONE);
} else {
const newTS =
keepLocalTime || keepCalendarTime // keepCalendarTime is the deprecated name for keepLocalTime
? this.ts + (this.o - zone.offset(this.ts)) * 60 * 1000
: this.ts;
return clone(this, { ts: newTS, zone });
}
}
/**
* "Set" the locale, numberingSystem, or outputCalendar. Returns a newly-constructed DateTime.
* @param {Object} properties - the properties to set
* @example DateTime.local(2017, 5, 25).reconfigure({ locale: 'en-GB' })
* @return {DateTime}
*/
reconfigure({ locale, numberingSystem, outputCalendar } = {}) {
const loc = this.loc.clone({ locale, numberingSystem, outputCalendar });
return clone(this, { loc });
}
/**
* "Set" the locale. Returns a newly-constructed DateTime.
* Just a convenient alias for reconfigure({ locale })
* @example DateTime.local(2017, 5, 25).setLocale('en-GB')
* @return {DateTime}
*/
setLocale(locale) {
return this.reconfigure({ locale });
}
/**
* "Set" the values of specified units. Returns a newly-constructed DateTime.
* You can only set units with this method; for "setting" metadata, see {@link reconfigure} and {@link setZone}.
* @param {Object} values - a mapping of units to numbers
* @example dt.set({ year: 2017 })
* @example dt.set({ hour: 8, minute: 30 })
* @example dt.set({ weekday: 5 })
* @example dt.set({ year: 2005, ordinal: 234 })
* @return {DateTime}
*/
set(values) {
if (!this.isValid) return this;
const normalized = normalizeObject(values, normalizeUnit),
settingWeekStuff =
!isUndefined(normalized.weekYear) ||
!isUndefined(normalized.weekNumber) ||
!isUndefined(normalized.weekday);
let mixed;
if (settingWeekStuff) {
mixed = weekToGregorian(Object.assign(gregorianToWeek(this.c), normalized));
} else if (!isUndefined(normalized.ordinal)) {
mixed = ordinalToGregorian(Object.assign(gregorianToOrdinal(this.c), normalized));
} else {
mixed = Object.assign(this.toObject(), normalized);
// if we didn't set the day but we ended up on an overflow date,
// use the last day of the right month
if (isUndefined(normalized.day)) {
mixed.day = Math.min(daysInMonth(mixed.year, mixed.month), mixed.day);
}
}
const [ts, o] = objToTS(mixed, this.o, this.zone);
return clone(this, { ts, o });
}
/**
* Add a period of time to this DateTime and return the resulting DateTime
*
* Adding hours, minutes, seconds, or milliseconds increases the timestamp by the right number of milliseconds. Adding days, months, or years shifts the calendar, accounting for DSTs and leap years along the way. Thus, `dt.plus({ hours: 24 })` may result in a different time than `dt.plus({ days: 1 })` if there's a DST shift in between.
* @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
* @example DateTime.local().plus(123) //~> in 123 milliseconds
* @example DateTime.local().plus({ minutes: 15 }) //~> in 15 minutes
* @example DateTime.local().plus({ days: 1 }) //~> this time tomorrow
* @example DateTime.local().plus({ days: -1 }) //~> this time yesterday
* @example DateTime.local().plus({ hours: 3, minutes: 13 }) //~> in 1 hr, 13 min
* @example DateTime.local().plus(Duration.fromObject({ hours: 3, minutes: 13 })) //~> in 1 hr, 13 min
* @return {DateTime}
*/
plus(duration) {
if (!this.isValid) return this;
const dur = friendlyDuration(duration);
return clone(this, adjustTime(this, dur));
}
/**
* Subtract a period of time to this DateTime and return the resulting DateTime
* See {@link plus}
* @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
@return {DateTime}
*/
minus(duration) {
if (!this.isValid) return this;
const dur = friendlyDuration(duration).negate();
return clone(this, adjustTime(this, dur));
}
/**
* "Set" this DateTime to the beginning of a unit of time.
* @param {string} unit - The unit to go to the beginning of. Can be 'year', 'month', 'day', 'hour', 'minute', 'second', or 'millisecond'.
* @example DateTime.local(2014, 3, 3).startOf('month').toISODate(); //=> '2014-03-01'
* @example DateTime.local(2014, 3, 3).startOf('year').toISODate(); //=> '2014-01-01'
* @example DateTime.local(2014, 3, 3, 5, 30).startOf('day').toISOTime(); //=> '00:00.000-05:00'
* @example DateTime.local(2014, 3, 3, 5, 30).startOf('hour').toISOTime(); //=> '05:00:00.000-05:00'
* @return {DateTime}
*/
startOf(unit) {
if (!this.isValid) return this;
const o = {},
normalizedUnit = Duration.normalizeUnit(unit);
switch (normalizedUnit) {
case 'years':
o.month = 1;
// falls through
case 'quarters':
case 'months':
o.day = 1;
// falls through
case 'weeks':
case 'days':
o.hour = 0;
// falls through
case 'hours':
o.minute = 0;
// falls through
case 'minutes':
o.second = 0;
// falls through
case 'seconds':
o.millisecond = 0;
break;
case 'milliseconds':
break;
default:
throw new InvalidUnitError(unit);
}
if (normalizedUnit === 'weeks') {
o.weekday = 1;
}
if (normalizedUnit === 'quarters') {
const q = Math.ceil(this.month / 3);
o.month = (q - 1) * 3 + 1;
}
return this.set(o);
}
/**
* "Set" this DateTime to the end (i.e. the last millisecond) of a unit of time
* @param {string} unit - The unit to go to the end of. Can be 'year', 'month', 'day', 'hour', 'minute', 'second', or 'millisecond'.
* @example DateTime.local(2014, 3, 3).endOf('month').toISO(); //=> '2014-03-31T23:59:59.999-05:00'
* @example DateTime.local(2014, 3, 3).endOf('year').toISO(); //=> '2014-12-31T23:59:59.999-05:00'
* @example DateTime.local(2014, 3, 3, 5, 30).endOf('day').toISO(); //=> '2014-03-03T23:59:59.999-05:00'
* @example DateTime.local(2014, 3, 3, 5, 30).endOf('hour').toISO(); //=> '2014-03-03T05:59:59.999-05:00'
* @return {DateTime}
*/
endOf(unit) {
return this.isValid
? this.startOf(unit)
.plus({ [unit]: 1 })
.minus(1)
: this;
}
// OUTPUT
/**
* Returns a string representation of this DateTime formatted according to the specified format string.
* **You may not want this.** See {@link toLocaleString} for a more flexible formatting tool. See the documentation for the specific format tokens supported.
* Defaults to en-US if no locale has been specified, regardless of the system's locale
* @param {string} fmt - the format string
* @param {Object} opts - options
* @param {boolean} opts.round - round numerical values
* @example DateTime.local().toFormat('yyyy LLL dd') //=> '2017 Apr 22'
* @example DateTime.local().setLocale('fr').toFormat('yyyy LLL dd') //=> '2017 avr. 22'
* @example DateTime.local().toFormat("HH 'hours and' mm 'minutes'") //=> '20 hours and 55 minutes'
* @return {string}
*/
toFormat(fmt, opts = {}) {
return this.isValid
? Formatter.create(this.loc.redefaultToEN(), opts).formatDateTimeFromString(this, fmt)
: INVALID;
}
/**
* Returns a localized string representing this date. Accepts the same options as the Intl.DateTimeFormat constructor and any presets defined by Luxon, such as `DateTime.DATE_FULL` or `DateTime.TIME_SIMPLE`.
* The exact behavior of this method is browser-specific, but in general it will return an appropriate representation.
* of the DateTime in the assigned locale.
* Defaults to the system's locale if no locale has been specified
* @see https://developer.mozilla.