UNPKG

luxon

Version:
6 lines 493 kB
[ { "__docId__": 0, "kind": "file", "name": "src/datetime.js", "content": "import { Duration } from './duration';\nimport { Interval } from './interval';\nimport { Settings } from './settings';\nimport { Formatter } from './impl/formatter';\nimport { FixedOffsetZone } from './zones/fixedOffsetZone';\nimport { LocalZone } from './zones/localZone';\nimport { Locale } from './impl/locale';\nimport { Util } from './impl/util';\nimport { RegexParser } from './impl/regexParser';\nimport { TokenParser } from './impl/tokenParser';\nimport { Conversions } from './impl/conversions';\nimport {\n InvalidArgumentError,\n ConflictingSpecificationError,\n InvalidUnitError,\n InvalidDateTimeError\n} from './errors';\n\nconst INVALID = 'Invalid DateTime',\n UNSUPPORTED_ZONE = 'unsupported zone',\n UNPARSABLE = 'unparsable';\n\nfunction possiblyCachedWeekData(dt) {\n if (dt.weekData === null) {\n dt.weekData = Conversions.gregorianToWeek(dt.c);\n }\n return dt.weekData;\n}\n\nfunction clone(inst, alts = {}) {\n const current = {\n ts: inst.ts,\n zone: inst.zone,\n c: inst.c,\n o: inst.o,\n loc: inst.loc,\n invalidReason: inst.invalidReason\n };\n return new DateTime(Object.assign({}, current, alts, { old: current }));\n}\n\nfunction fixOffset(localTS, o, tz) {\n // Our UTC time is just a guess because our offset is just a guess\n let utcGuess = localTS - o * 60 * 1000;\n\n // Test whether the zone matches the offset for this ts\n const o2 = tz.offset(utcGuess);\n\n // If so, offset didn't change and we're done\n if (o === o2) {\n return [utcGuess, o];\n }\n\n // If not, change the ts by the difference in the offset\n utcGuess -= (o2 - o) * 60 * 1000;\n\n // If that gives us the local time we want, we're done\n const o3 = tz.offset(utcGuess);\n if (o2 === o3) {\n return [utcGuess, o2];\n }\n\n // If it's different, we're in a hole time. The offset has changed, but the we don't adjust the time\n return [localTS - Math.min(o2, o3) * 60 * 1000, Math.max(o2, o3)];\n}\n\nfunction tsToObj(ts, offset) {\n ts += offset * 60 * 1000;\n\n const d = new Date(ts);\n\n return {\n year: d.getUTCFullYear(),\n month: d.getUTCMonth() + 1,\n day: d.getUTCDate(),\n hour: d.getUTCHours(),\n minute: d.getUTCMinutes(),\n second: d.getUTCSeconds(),\n millisecond: d.getUTCMilliseconds()\n };\n}\n\nfunction objToLocalTS(obj) {\n let d = Date.UTC(\n obj.year,\n obj.month - 1,\n obj.day,\n obj.hour,\n obj.minute,\n obj.second,\n obj.millisecond\n );\n\n // javascript is stupid and i hate it\n if (obj.year < 100 && obj.year >= 0) {\n d = new Date(d);\n d.setFullYear(obj.year);\n }\n return +d;\n}\n\nfunction objToTS(obj, offset, zone) {\n return fixOffset(objToLocalTS(obj), offset, zone);\n}\n\nfunction adjustTime(inst, dur) {\n const oPre = inst.o,\n c = Object.assign({}, inst.c, {\n year: inst.c.year + dur.years,\n month: inst.c.month + dur.months,\n day: inst.c.day + dur.days + dur.weeks * 7\n }),\n millisToAdd = Duration.fromObject({\n hours: dur.hours,\n minutes: dur.minutes,\n seconds: dur.seconds,\n milliseconds: dur.milliseconds\n }).as('milliseconds'),\n localTS = objToLocalTS(c);\n\n let [ts, o] = fixOffset(localTS, oPre, inst.zone);\n\n if (millisToAdd !== 0) {\n ts += millisToAdd;\n // that could have changed the offset by going over a DST, but we want to keep the ts the same\n o = inst.zone.offset(ts);\n }\n\n return { ts, o };\n}\n\nfunction parseDataToDateTime(parsed, parsedZone, opts = {}) {\n const { setZone, zone } = opts;\n if (parsed && Object.keys(parsed).length !== 0) {\n const interpretationZone = parsedZone || zone,\n inst = DateTime.fromObject(\n Object.assign(parsed, opts, {\n zone: interpretationZone\n })\n );\n return setZone ? inst : inst.setZone(zone);\n } else {\n return DateTime.invalid(UNPARSABLE);\n }\n}\n\nfunction formatMaybe(dt, format) {\n return dt.isValid\n ? Formatter.create(Locale.create('en')).formatDateTimeFromString(dt, format)\n : null;\n}\n\nconst defaultUnitValues = {\n month: 1,\n day: 1,\n hour: 0,\n minute: 0,\n second: 0,\n millisecond: 0\n },\n defaultWeekUnitValues = {\n weekNumber: 1,\n weekday: 1,\n hour: 0,\n minute: 0,\n second: 0,\n millisecond: 0\n },\n defaultOrdinalUnitValues = {\n ordinal: 1,\n hour: 0,\n minute: 0,\n second: 0,\n millisecond: 0\n };\n\nfunction isoTimeFormat(dateTime, suppressSecs, suppressMillis) {\n return suppressSecs && dateTime.second === 0 && dateTime.millisecond === 0\n ? 'HH:mmZ'\n : suppressMillis && dateTime.millisecond === 0 ? 'HH:mm:ssZZ' : 'HH:mm:ss.SSSZZ';\n}\n\nconst orderedUnits = ['year', 'month', 'day', 'hour', 'minute', 'second', 'millisecond'];\n\nconst orderedWeekUnits = [\n 'weekYear',\n 'weekNumber',\n 'weekday',\n 'hour',\n 'minute',\n 'second',\n 'millisecond'\n];\n\nconst orderedOrdinalUnits = ['year', 'ordinal', 'hour', 'minute', 'second', 'millisecond'];\n\nfunction normalizeUnit(unit, ignoreUnknown = false) {\n const normalized = {\n year: 'year',\n years: 'year',\n month: 'month',\n months: 'month',\n day: 'day',\n days: 'day',\n hour: 'hour',\n hours: 'hour',\n minute: 'minute',\n minutes: 'minute',\n second: 'second',\n seconds: 'second',\n millisecond: 'millisecond',\n milliseconds: 'millisecond',\n weekday: 'weekday',\n weekdays: 'weekday',\n weeknumber: 'weekNumber',\n weeksnumber: 'weekNumber',\n weeknumbers: 'weekNumber',\n weekyear: 'weekYear',\n weekyears: 'weekYear',\n ordinal: 'ordinal'\n }[unit ? unit.toLowerCase() : unit];\n\n if (!ignoreUnknown && !normalized) throw new InvalidUnitError(unit);\n\n return normalized;\n}\n\n/**\n * 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.\n *\n * A DateTime comprises of:\n * * A timestamp. Each DateTime instance refers to a specific millisecond of the Unix epoch.\n * * A time zone. Each instance is considered in the context of a specific zone (by default the local system's zone).\n * * Configuration properties that effect how output strings are formatted, such as `locale`, `numberingSystem`, and `outputCalendar`.\n *\n * Here is a brief overview of the most commonly used functionality it provides:\n *\n * * **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 fromString}. To create one from a native JS date, use {@link fromJSDate}.\n * * **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},\n * {@link day}, {@link hour}, {@link minute}, {@link second}, {@link millisecond} accessors.\n * * **Week calendar**: For ISO week calendar attributes, see the {@link weekYear}, {@link weekNumber}, and {@link weekday} accessors.\n * * **Configuration** See the {@link locale} and {@link numberingSystem} accessors.\n * * **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}.\n * * **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}, and {@link valueOf}.\n *\n * 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.\n */\nexport class DateTime {\n /**\n * @access private\n */\n constructor(config = {}) {\n const zone = config.zone || Settings.defaultZone,\n invalidReason = config.invalidReason || (zone.isValid ? null : UNSUPPORTED_ZONE);\n\n Object.defineProperty(this, 'ts', {\n value: config.ts || Settings.now(),\n enumerable: true\n });\n\n Object.defineProperty(this, 'zone', {\n value: zone,\n enumerable: true\n });\n\n Object.defineProperty(this, 'loc', {\n value: config.loc || Locale.create(),\n enumerable: true\n });\n\n Object.defineProperty(this, 'invalidReason', {\n value: invalidReason,\n enumerable: false\n });\n\n Object.defineProperty(this, 'weekData', {\n writable: true, // !!!\n value: null,\n enumerable: false\n });\n\n if (!invalidReason) {\n const unchanged =\n config.old && config.old.ts === this.ts && config.old.zone.equals(this.zone),\n c = unchanged ? config.old.c : tsToObj(this.ts, this.zone.offset(this.ts)),\n o = unchanged ? config.old.o : this.zone.offset(this.ts);\n\n Object.defineProperty(this, 'c', { value: c });\n Object.defineProperty(this, 'o', { value: o });\n }\n }\n\n // CONSTRUCT\n\n /**\n * Create a local DateTime\n * @param {number} year - The calendar year. If omitted (as in, call `local()` with no arguments), the current time will be used\n * @param {number} [month=1] - The month, 1-indexed\n * @param {number} [day=1] - The day of the month\n * @param {number} [hour=0] - The hour of the day, in 24-hour time\n * @param {number} [minute=0] - The minute of the hour, i.e. a number between 0 and 59\n * @param {number} [second=0] - The second of the minute, i.e. a number between 0 and 59\n * @param {number} [millisecond=0] - The millisecond of the second, i.e. a number between 0 and 999\n * @example DateTime.local() //~> now\n * @example DateTime.local(2017) //~> 2017-01-01T00:00:00\n * @example DateTime.local(2017, 3) //~> 2017-03-01T00:00:00\n * @example DateTime.local(2017, 3, 12) //~> 2017-03-12T00:00:00\n * @example DateTime.local(2017, 3, 12, 5) //~> 2017-03-12T05:00:00\n * @example DateTime.local(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00\n * @example DateTime.local(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10\n * @example DateTime.local(2017, 3, 12, 5, 45, 10, 765) //~> 2017-03-12T05:45:10.675\n * @return {DateTime}\n */\n static local(year, month, day, hour, minute, second, millisecond) {\n if (Util.isUndefined(year)) {\n return new DateTime({ ts: Settings.now() });\n } else {\n return DateTime.fromObject({\n year,\n month,\n day,\n hour,\n minute,\n second,\n millisecond,\n zone: Settings.defaultZone\n });\n }\n }\n\n /**\n * Create a DateTime in UTC\n * @param {number} year - The calendar year. If omitted (as in, call `utc()` with no arguments), the current time will be used\n * @param {number} [month=1] - The month, 1-indexed\n * @param {number} [day=1] - The day of the month\n * @param {number} [hour=0] - The hour of the day, in 24-hour time\n * @param {number} [minute=0] - The minute of the hour, i.e. a number between 0 and 59\n * @param {number} [second=0] - The second of the minute, i.e. a number between 0 and 59\n * @param {number} [millisecond=0] - The millisecond of the second, i.e. a number between 0 and 999\n * @example DateTime.utc() //~> now\n * @example DateTime.utc(2017) //~> 2017-01-01T00:00:00Z\n * @example DateTime.utc(2017, 3) //~> 2017-03-01T00:00:00Z\n * @example DateTime.utc(2017, 3, 12) //~> 2017-03-12T00:00:00Z\n * @example DateTime.utc(2017, 3, 12, 5) //~> 2017-03-12T05:00:00Z\n * @example DateTime.utc(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00Z\n * @example DateTime.utc(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10Z\n * @example DateTime.utc(2017, 3, 12, 5, 45, 10, 765) //~> 2017-03-12T05:45:10.675Z\n * @return {DateTime}\n */\n static utc(year, month, day, hour, minute, second, millisecond) {\n if (Util.isUndefined(year)) {\n return new DateTime({\n ts: Settings.now(),\n zone: FixedOffsetZone.utcInstance\n });\n } else {\n return DateTime.fromObject({\n year,\n month,\n day,\n hour,\n minute,\n second,\n millisecond,\n zone: FixedOffsetZone.utcInstance\n });\n }\n }\n\n /**\n * Create an DateTime from a Javascript Date object. Uses the default zone.\n * @param {Date|Any} date - a Javascript Date object\n * @param {Object} options - configuration options for the DateTime\n * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into\n * @return {DateTime}\n */\n static fromJSDate(date, options = {}) {\n return new DateTime({\n ts: new Date(date).valueOf(),\n zone: Util.normalizeZone(options.zone),\n loc: Locale.fromObject(options)\n });\n }\n\n /**\n * Create an DateTime from a count of epoch milliseconds. Uses the default zone.\n * @param {number} milliseconds - a number of milliseconds since 1970 UTC\n * @param {Object} options - configuration options for the DateTime\n * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into\n * @param {string} [options.locale='en-US'] - a locale to set on the resulting DateTime instance\n * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance\n * @return {DateTime}\n */\n static fromMillis(milliseconds, options = {}) {\n return new DateTime({\n ts: milliseconds,\n zone: Util.normalizeZone(options.zone),\n loc: Locale.fromObject(options)\n });\n }\n\n /**\n * Create an DateTime from a Javascript object with keys like 'year' and 'hour' with reasonable defaults.\n * @param {Object} obj - the object to create the DateTime from\n * @param {number} obj.year - a year, such as 1987\n * @param {number} obj.month - a month, 1-12\n * @param {number} obj.day - a day of the month, 1-31, depending on the month\n * @param {number} obj.ordinal - day of the year, 1-365 or 366\n * @param {number} obj.weekYear - an ISO week year\n * @param {number} obj.weekNumber - an ISO week number, between 1 and 52 or 53, depending on the year\n * @param {number} obj.weekday - an ISO weekday, 1-7, where 1 is Monday and 7 is Sunday\n * @param {number} obj.hour - hour of the day, 0-23\n * @param {number} obj.minute - minute of the hour, 0-59\n * @param {number} obj.second - second of the minute, 0-59\n * @param {number} obj.millisecond - millisecond of the second, 0-999\n * @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()\n * @param {string} [obj.locale='en-US'] - a locale to set on the resulting DateTime instance\n * @param {string} obj.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @param {string} obj.numberingSystem - the numbering system to set on the resulting DateTime instance\n * @example DateTime.fromObject({ year: 1982, month: 5, day: 25}).toISODate() //=> '1982-05-25'\n * @example DateTime.fromObject({ year: 1982 }).toISODate() //=> '1982-01-01T00'\n * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }) //~> today at 10:26:06\n * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6, zone: 'utc' }),\n * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6, zone: 'local' })\n * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6, zone: 'America/New_York' })\n * @example DateTime.fromObject({ weekYear: 2016, weekNumber: 2, weekday: 3 }).toISODate() //=> '2016-01-13'\n * @return {DateTime}\n */\n static fromObject(obj) {\n const zoneToUse = Util.normalizeZone(obj.zone);\n if (!zoneToUse.isValid) {\n return DateTime.invalid(UNSUPPORTED_ZONE);\n }\n\n const tsNow = Settings.now(),\n offsetProvis = zoneToUse.offset(tsNow),\n normalized = Util.normalizeObject(obj, normalizeUnit, true),\n containsOrdinal = !Util.isUndefined(normalized.ordinal),\n containsGregorYear = !Util.isUndefined(normalized.year),\n containsGregorMD = !Util.isUndefined(normalized.month) || !Util.isUndefined(normalized.day),\n containsGregor = containsGregorYear || containsGregorMD,\n definiteWeekDef = normalized.weekYear || normalized.weekNumber,\n loc = Locale.fromObject(obj);\n\n // cases:\n // just a weekday -> this week's instance of that weekday, no worries\n // (gregorian data or ordinal) + (weekYear or weekNumber) -> error\n // (gregorian month or day) + ordinal -> error\n // otherwise just use weeks or ordinals or gregorian, depending on what's specified\n\n if ((containsGregor || containsOrdinal) && definiteWeekDef) {\n throw new ConflictingSpecificationError(\n \"Can't mix weekYear/weekNumber units with year/month/day or ordinals\"\n );\n }\n\n if (containsGregorMD && containsOrdinal) {\n throw new ConflictingSpecificationError(\"Can't mix ordinal dates with month/day\");\n }\n\n const useWeekData = definiteWeekDef || (normalized.weekday && !containsGregor);\n\n // configure ourselves to deal with gregorian dates or week stuff\n let units,\n defaultValues,\n objNow = tsToObj(tsNow, offsetProvis);\n if (useWeekData) {\n units = orderedWeekUnits;\n defaultValues = defaultWeekUnitValues;\n objNow = Conversions.gregorianToWeek(objNow);\n } else if (containsOrdinal) {\n units = orderedOrdinalUnits;\n defaultValues = defaultOrdinalUnitValues;\n objNow = Conversions.gregorianToOrdinal(objNow);\n } else {\n units = orderedUnits;\n defaultValues = defaultUnitValues;\n }\n\n // set default values for missing stuff\n let foundFirst = false;\n for (const u of units) {\n const v = normalized[u];\n if (!Util.isUndefined(v)) {\n foundFirst = true;\n } else if (foundFirst) {\n normalized[u] = defaultValues[u];\n } else {\n normalized[u] = objNow[u];\n }\n }\n\n // make sure the values we have are in range\n const higherOrderInvalid = useWeekData\n ? Conversions.hasInvalidWeekData(normalized)\n : containsOrdinal\n ? Conversions.hasInvalidOrdinalData(normalized)\n : Conversions.hasInvalidGregorianData(normalized),\n invalidReason = higherOrderInvalid || Conversions.hasInvalidTimeData(normalized);\n\n if (invalidReason) {\n return DateTime.invalid(invalidReason);\n }\n\n // compute the actual time\n const gregorian = useWeekData\n ? Conversions.weekToGregorian(normalized)\n : containsOrdinal ? Conversions.ordinalToGregorian(normalized) : normalized,\n [tsFinal, offsetFinal] = objToTS(gregorian, offsetProvis, zoneToUse),\n inst = new DateTime({\n ts: tsFinal,\n zone: zoneToUse,\n o: offsetFinal,\n loc\n });\n\n // gregorian data + weekday serves only to validate\n if (normalized.weekday && containsGregor && obj.weekday !== inst.weekday) {\n return DateTime.invalid('mismatched weekday');\n }\n\n return inst;\n }\n\n /**\n * Create a DateTime from an ISO 8601 string\n * @param {string} text - the ISO string\n * @param {Object} opts - options to affect the creation\n * @param {boolean} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the time to this zone\n * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one\n * @param {string} [opts.locale='en-US'] - a locale to set on the resulting DateTime instance\n * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance\n * @example DateTime.fromISO('2016-05-25T09:08:34.123')\n * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00')\n * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00', {setZone: true})\n * @example DateTime.fromISO('2016-05-25T09:08:34.123', {zone: 'utc')\n * @example DateTime.fromISO('2016-W05-4')\n * @return {DateTime}\n */\n static fromISO(text, opts = {}) {\n const [vals, parsedZone] = RegexParser.parseISODate(text);\n return parseDataToDateTime(vals, parsedZone, opts);\n }\n\n /**\n * Create a DateTime from an RFC 2822 string\n * @param {string} text - the RFC 2822 string\n * @param {Object} opts - options to affect the creation\n * @param {boolean} [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.\n * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one\n * @param {string} [opts.locale='en-US'] - a locale to set on the resulting DateTime instance\n * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance\n * @example DateTime.fromRFC2822('25 Nov 2016 13:23:12 GMT')\n * @example DateTime.fromRFC2822('Tue, 25 Nov 2016 13:23:12 +0600')\n * @example DateTime.fromRFC2822('25 Nov 2016 13:23 Z')\n * @return {DateTime}\n */\n static fromRFC2822(text, opts = {}) {\n const [vals, parsedZone] = RegexParser.parseRFC2822Date(text);\n return parseDataToDateTime(vals, parsedZone, opts);\n }\n\n /**\n * Create a DateTime from an HTTP header date\n * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1\n * @param {string} text - the HTTP header date\n * @param {object} options - options to affect the creation\n * @param {boolean} [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.\n * @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.\n * @param {string} [options.locale='en-US'] - a locale to set on the resulting DateTime instance\n * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance\n * @example DateTime.fromHTTP('Sun, 06 Nov 1994 08:49:37 GMT')\n * @example DateTime.fromHTTP('Sunday, 06-Nov-94 08:49:37 GMT')\n * @example DateTime.fromHTTP('Sun Nov 6 08:49:37 1994')\n * @return {DateTime}\n */\n static fromHTTP(text, options = {}) {\n const [vals, parsedZone] = RegexParser.parseHTTPDate(text);\n return parseDataToDateTime(vals, parsedZone, options);\n }\n\n /**\n * Create a DateTime from an input string and format string\n * @param {string} text - the string to parse\n * @param {string} fmt - the format the string is expected to be in (see description)\n * @param {Object} options - options to affect the creation\n * @param {boolean} [options.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone\n * @param {boolean} [options.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one\n * @param {string} [options.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale\n * @param {string} options.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system\n * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @return {DateTime}\n */\n static fromString(text, fmt, options = {}) {\n const { locale = null, numberingSystem = null } = options,\n parser = new TokenParser(Locale.fromOpts({ locale, numberingSystem })),\n [vals, parsedZone, invalidReason] = parser.parseDateTime(text, fmt);\n if (invalidReason) {\n return DateTime.invalid(invalidReason);\n } else {\n return parseDataToDateTime(vals, parsedZone, options);\n }\n }\n\n /**\n * Create an invalid DateTime.\n * @return {DateTime}\n */\n static invalid(reason) {\n if (!reason) {\n throw new InvalidArgumentError('need to specify a reason the DateTime is invalid');\n }\n if (Settings.throwOnInvalid) {\n throw new InvalidDateTimeError(reason);\n } else {\n return new DateTime({ invalidReason: reason });\n }\n }\n\n // INFO\n\n /**\n * Get the value of unit.\n * @param {string} unit - a unit such as 'minute' or 'day'\n * @example DateTime.local(2017, 7, 4).get('month'); //=> 7\n * @example DateTime.local(2017, 7, 4).get('day'); //=> 4\n * @return {number}\n */\n get(unit) {\n return this[unit];\n }\n\n /**\n * Returns whether the DateTime is valid. Invalid DateTimes occur when:\n * * The DateTime was created from invalid calendar information, such as the 13th month or February 30\n * * The DateTime was created by an operation on another invalid date\n * @return {boolean}\n */\n get isValid() {\n return this.invalidReason === null;\n }\n\n /**\n * Returns an explanation of why this DateTime became invalid, or null if the DateTime is valid\n * @return {string}\n */\n get invalidReason() {\n return this.invalidReason;\n }\n\n /**\n * Get the locale of a DateTime, such 'en-GB'. The locale is used when formatting the DateTime\n *\n * @return {string}\n */\n get locale() {\n return this.loc.locale;\n }\n\n /**\n * Get the numbering system of a DateTime, such 'beng'. The numbering system is used when formatting the DateTime\n *\n * @return {string}\n */\n get numberingSystem() {\n return this.loc.numberingSystem;\n }\n\n /**\n * Get the output calendar of a DateTime, such 'islamic'. The output calendar is used when formatting the DateTime\n *\n * @return {string}\n */\n get outputCalendar() {\n return this.loc.outputCalendar;\n }\n\n /**\n * Get the name of the time zone.\n * @return {String}\n */\n get zoneName() {\n return this.zone.name;\n }\n\n /**\n * Get the year\n * @example DateTime.local(2017, 5, 25).year //=> 2017\n * @return {number}\n */\n get year() {\n return this.isValid ? this.c.year : NaN;\n }\n\n /**\n * Get the month (1-12).\n * @example DateTime.local(2017, 5, 25).month //=> 5\n * @return {number}\n */\n get month() {\n return this.isValid ? this.c.month : NaN;\n }\n\n /**\n * Get the day of the month (1-30ish).\n * @example DateTime.local(2017, 5, 25).day //=> 25\n * @return {number}\n */\n get day() {\n return this.isValid ? this.c.day : NaN;\n }\n\n /**\n * Get the hour of the day (0-23).\n * @example DateTime.local(2017, 5, 25, 9).hour //=> 9\n * @return {number}\n */\n get hour() {\n return this.isValid ? this.c.hour : NaN;\n }\n\n /**\n * Get the minute of the hour (0-59).\n * @example DateTime.local(2017, 5, 25, 9, 30).minute //=> 30\n * @return {number}\n */\n get minute() {\n return this.isValid ? this.c.minute : NaN;\n }\n\n /**\n * Get the second of the minute (0-59).\n * @example DateTime.local(2017, 5, 25, 9, 30, 52).second //=> 52\n * @return {number}\n */\n get second() {\n return this.isValid ? this.c.second : NaN;\n }\n\n /**\n * Get the millisecond of the second (0-999).\n * @example DateTime.local(2017, 5, 25, 9, 30, 52, 654).millisecond //=> 654\n * @return {number}\n */\n get millisecond() {\n return this.isValid ? this.c.millisecond : NaN;\n }\n\n /**\n * Get the week year\n * @see https://en.wikipedia.org/wiki/ISO_week_date\n * @example DateTime.local(2014, 11, 31).weekYear //=> 2015\n * @return {number}\n */\n get weekYear() {\n return this.isValid ? possiblyCachedWeekData(this).weekYear : NaN;\n }\n\n /**\n * Get the week number of the week year (1-52ish).\n * @see https://en.wikipedia.org/wiki/ISO_week_date\n * @example DateTime.local(2017, 5, 25).weekNumber //=> 21\n * @return {number}\n */\n get weekNumber() {\n return this.isValid ? possiblyCachedWeekData(this).weekNumber : NaN;\n }\n\n /**\n * Get the day of the week.\n * 1 is Monday and 7 is Sunday\n * @see https://en.wikipedia.org/wiki/ISO_week_date\n * @example DateTime.local(2014, 11, 31).weekday //=> 4\n * @return {number}\n */\n get weekday() {\n return this.isValid ? possiblyCachedWeekData(this).weekday : NaN;\n }\n\n /**\n * Get the ordinal (i.e. the day of the year)\n * @example DateTime.local(2017, 5, 25).ordinal //=> 145\n * @return {number|DateTime}\n */\n get ordinal() {\n return this.isValid ? Conversions.gregorianToOrdinal(this.c).ordinal : NaN;\n }\n\n /**\n * Get the UTC offset of this DateTime in minutes\n * @example DateTime.local().offset //=> -240\n * @example DateTime.utc().offset //=> 0\n * @return {number}\n */\n get offset() {\n return this.isValid ? this.zone.offset(this.ts) : NaN;\n }\n\n /**\n * Get the short human name for the zone's current offset, for example \"EST\" or \"EDT\".\n * @return {String}\n */\n get offsetNameShort() {\n if (this.isValid) {\n return this.zone.offsetName(this.ts, {\n format: 'short',\n locale: this.locale\n });\n } else {\n return null;\n }\n }\n\n /**\n * Get the long human name for the zone's current offset, for example \"Eastern Standard Time\" or \"Eastern Daylight Time\".\n * Is locale-aware.\n * @return {String}\n */\n get offsetNameLong() {\n if (this.isValid) {\n return this.zone.offsetName(this.ts, {\n format: 'long',\n locale: this.locale\n });\n } else {\n return null;\n }\n }\n\n /**\n * Get whether this zone's offset ever changes, as in a DST.\n * @return {boolean}\n */\n get isOffsetFixed() {\n return this.zone.universal;\n }\n\n /**\n * Get whether the DateTime is in a DST.\n * @return {boolean}\n */\n get isInDST() {\n if (this.isOffsetFixed) {\n return false;\n } else {\n return (\n this.offset > this.set({ month: 1 }).offset || this.offset > this.set({ month: 5 }).offset\n );\n }\n }\n\n /**\n * Returns true if this DateTime is in a leap year, false otherwise\n * @example DateTime.local(2016).isInLeapYear //=> true\n * @example DateTime.local(2013).isInLeapYear //=> false\n * @return {boolean}\n */\n get isInLeapYear() {\n return Util.isLeapYear(this.year);\n }\n\n /**\n * Returns the number of days in this DateTime's month\n * @example DateTime.local(2016, 2).daysInMonth //=> 29\n * @example DateTime.local(2016, 3).days //=> 31\n * @return {number}\n */\n get daysInMonth() {\n return Util.daysInMonth(this.year, this.month);\n }\n\n /**\n * Returns the number of days in this DateTime's year\n * @example DateTime.local(2016).daysInYear //=> 366\n * @example DateTime.local(2013).daysInYear //=> 365\n * @return {number}\n */\n get daysInYear() {\n return this.isValid ? Util.daysInYear(this.year) : NaN;\n }\n\n /**\n * Returns the resolved Intl options for this DateTime.\n * This is useful in understanding the behavior of parsing and formatting methods\n * @param {object} opts - the same options as toLocaleString\n * @return {object}\n */\n resolvedLocaleOpts(opts = {}) {\n const { locale, numberingSystem, calendar } = Formatter.create(\n this.loc.clone(opts),\n opts\n ).resolvedOptions(this);\n return { locale, numberingSystem, outputCalendar: calendar };\n }\n\n // TRANSFORM\n\n /**\n * \"Set\" the DateTime's zone to UTC. Returns a newly-constructed DateTime.\n *\n * Equivalent to {@link setZone}('utc')\n * @param {number} [offset=0] - optionally, an offset from UTC in minutes\n * @param {object} [opts={}] - options to pass to `setZone()`\n * @return {DateTime}\n */\n toUTC(offset = 0, opts = {}) {\n return this.setZone(FixedOffsetZone.instance(offset), opts);\n }\n\n /**\n * \"Set\" the DateTime's zone to the host's local zone. Returns a newly-constructed DateTime.\n *\n * Equivalent to `setZone('local')`\n * @return {DateTime}\n */\n toLocal() {\n return this.setZone(new LocalZone());\n }\n\n /**\n * \"Set\" the DateTime's zone to specified zone. Returns a newly-constructed DateTime.\n *\n * 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.\n * @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.\n * @param {object} opts - options\n * @param {boolean} [opts.keepCalendarTime=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.\n * @return {DateTime}\n */\n setZone(zone, { keepCalendarTime = false } = {}) {\n zone = Util.normalizeZone(zone);\n if (zone.equals(this.zone)) {\n return this;\n } else if (!zone.isValid) {\n return DateTime.invalid(UNSUPPORTED_ZONE);\n } else {\n const newTS = keepCalendarTime\n ? this.ts + (this.o - zone.offset(this.ts)) * 60 * 1000\n : this.ts;\n return clone(this, { ts: newTS, zone });\n }\n }\n\n /**\n * \"Set\" the locale, numberingSystem, or outputCalendar. Returns a newly-constructed DateTime.\n * @param {object} properties - the properties to set\n * @example DateTime.local(2017, 5, 25).reconfigure({ locale: 'en-GB' })\n * @return {DateTime}\n */\n reconfigure({ locale, numberingSystem, outputCalendar } = {}) {\n const loc = this.loc.clone({ locale, numberingSystem, outputCalendar });\n return clone(this, { loc });\n }\n\n /**\n * \"Set\" the locale. Returns a newly-constructed DateTime.\n * Just a convenient alias for reconfigure({ locale })\n * @example DateTime.local(2017, 5, 25).setLocale('en-GB')\n * @return {DateTime}\n */\n setLocale(locale) {\n return this.reconfigure({ locale });\n }\n\n /**\n * \"Set\" the values of specified units. Returns a newly-constructed DateTime.\n * @param {object} values - a mapping of units to numbers\n * @example dt.set({ year: 2017 })\n * @example dt.set({ hour: 8, minute: 30 })\n * @example dt.set({ weekday: 5 })\n * @example dt.set({ year: 2005, ordinal: 234 })\n * @example dt.set({ outputCalendar: 'beng', zone: 'utc' })\n * @return {DateTime}\n */\n set(values) {\n const normalized = Util.normalizeObject(values, normalizeUnit),\n settingWeekStuff =\n !Util.isUndefined(normalized.weekYear) ||\n !Util.isUndefined(normalized.weekNumber) ||\n !Util.isUndefined(normalized.weekday);\n\n let mixed;\n if (settingWeekStuff) {\n mixed = Conversions.weekToGregorian(\n Object.assign(Conversions.gregorianToWeek(this.c), normalized)\n );\n } else if (!Util.isUndefined(normalized.ordinal)) {\n mixed = Conversions.ordinalToGregorian(\n Object.assign(Conversions.gregorianToOrdinal(this.c), normalized)\n );\n } else {\n mixed = Object.assign(this.toObject(), normalized);\n\n // if we didn't set the day but we ended up on an overflow date,\n // use the last day of the right month\n if (Util.isUndefined(normalized.day)) {\n mixed.day = Math.min(Util.daysInMonth(mixed.year, mixed.month), mixed.day);\n }\n }\n\n const [ts, o] = objToTS(mixed, this.o, this.zone);\n return clone(this, { ts, o });\n }\n\n /**\n * Add a period of time to this DateTime and return the resulting DateTime\n *\n * 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.\n * @param {Duration|number|object} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()\n * @example DateTime.local().plus(123) //~> in 123 milliseconds\n * @example DateTime.local().plus({ minutes: 15 }) //~> in 15 minutes\n * @example DateTime.local().plus({ days: 1 }) //~> this time tomorrow\n * @example DateTime.local().plus({ hours: 3, minutes: 13 }) //~> in 1 hr, 13 min\n * @example DateTime.local().plus(Duration.fromObject({ hours: 3, minutes: 13 })) //~> in 1 hr, 13 min\n * @return {DateTime}\n */\n plus(duration) {\n if (!this.isValid) return this;\n const dur = Util.friendlyDuration(duration);\n return clone(this, adjustTime(this, dur));\n }\n\n /**\n * Subtract a period of time to this DateTime and return the resulting DateTime\n * See {@link plus}\n * @param {Duration|number|object} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()\n @return {DateTime}\n */\n minus(duration) {\n if (!this.isValid) return this;\n const dur = Util.friendlyDuration(duration).negate();\n return clone(this, adjustTime(this, dur));\n }\n\n /**\n * \"Set\" this DateTime to the beginning of a unit of time.\n * @param {string} unit - The unit to go to the beginning of. Can be 'year', 'month', 'day', 'hour', 'minute', 'second', or 'millisecond'.\n * @example DateTime.local(2014, 3, 3).startOf('month').toISODate(); //=> '2014-03-01'\n * @example DateTime.local(2014, 3, 3).startOf('year').toISODate(); //=> '2014-01-01'\n * @example DateTime.local(2014, 3, 3, 5, 30).startOf('day').toISOTime(); //=> '00:00.000-05:00'\n * @example DateTime.local(2014, 3, 3, 5, 30).startOf('hour').toISOTime(); //=> '05:00:00.000-05:00'\n * @return {DateTime}\n */\n startOf(unit) {\n if (!this.isValid) return this;\n const o = {},\n normalizedUnit = Duration.normalizeUnit(unit);\n switch (normalizedUnit) {\n case 'years':\n o.month = 1;\n // falls through\n case 'months':\n o.day = 1;\n // falls through\n case 'weeks':\n case 'days':\n o.hour = 0;\n // falls through\n case 'hours':\n o.minute = 0;\n // falls through\n case 'minutes':\n o.second = 0;\n // falls through\n case 'seconds':\n o.millisecond = 0;\n break;\n default:\n throw new InvalidUnitError(unit);\n }\n\n if (normalizedUnit === 'weeks') {\n o.weekday = 1;\n }\n\n return this.set(o);\n }\n\n /**\n * \"Set\" this DateTime to the end (i.e. the last millisecond) of a unit of time\n * @param {string} unit - The unit to go to the end of. Can be 'year', 'month', 'day', 'hour', 'minute', 'second', or 'millisecond'.\n * @example DateTime.local(2014, 3, 3).endOf('month').toISO(); //=> '2014-03-03T00:00:00.000-05:00'\n * @example DateTime.local(2014, 3, 3).endOf('year').toISO(); //=> '2014-12-31T23:59:59.999-05:00'\n * @example DateTime.local(2014, 3, 3, 5, 30).endOf('day').toISO(); //=> '2014-03-03T23:59:59.999-05:00'\n * @example DateTime.local(2014, 3, 3, 5, 30).endOf('hour').toISO(); //=> '2014-03-03T05:59:59.999-05:00'\n * @return {DateTime}\n */\n endOf(unit) {\n return this.isValid\n ? this.startOf(unit)\n .plus({ [unit]: 1 })\n .minus(1)\n : this;\n }\n\n // OUTPUT\n\n /**\n * Returns a string representation of this DateTime formatted according to the specified format string.\n * **You may not want this.** See {@link toLocaleString} for a more flexible formatting tool. See the documentation for the specific format tokens supported.\n * @param {string} fmt - the format string\n * @param {object} opts - options\n * @param {boolean} opts.round - round numerical values\n * @example DateTime.local().toFormat('yyyy LLL dd') //=> '2017 avr. 22'\n * @example DateTime.local().setLocale('fr').toFormat('yyyy LLL dd') //=> '2017 Apr 22'\n * @example DateTime.local().toFormat(\"HH 'hours and' mm 'minutes'\") //=> '20 hours and 55 minutes'\n * @return {string}\n */\n toFormat(fmt, opts = {}) {\n return this.isValid\n ? Formatter.create(this.loc, opts).formatDateTimeFromString(this, fmt)\n : INVALID;\n }\n\n /**\n * 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`.\n * The exact behavior of this method is browser-specific, but in general it will return an appropriate representation.\n * of the DateTime in the assigned locale.\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat\n * @param opts {object} - Intl.DateTimeFormat constructor options\n * @example DateTime.local().toLocaleString(); //=> 4/20/2017\n * @example DateTime.local().setLocale('en-gb').toLocaleString(); //=> '20/04/2017'\n * @example DateTime.local().toLocaleString(DateTime.DATE_FULL); //=> 'April 20, 2017'\n * @example DateTime.local().toLocaleString(DateTime.TIME_SIMPLE); //=> '11:32 AM'\n * @example DateTime.local().toLocaleString(DateTime.DATETIME_SHORT); //=> '4/20/2017, 11:32 AM'\n * @example DateTime.local().toLocaleString({weekday: 'long', month: 'long', day: '2-digit'}); //=> 'Thu, Apr 20'\n * @example DateTime.local().toLocaleString({weekday: 'long', month: 'long', day: '2-digit', hour: '2-digit', minute: '2-digit'}); //=> 'Thu, Apr 20, 11:27'\n * @example DateTime.local().toLocaleString({hour: '2-digit', minute: '2-digit'}); //=> '11:32'\n * @return {string}\n */\n toLocaleString(opts = {}) {\n return this.isValid\n ? Formatter.create(this.loc.clone(opts), opts).formatDateTime(this)\n : INVALID;\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of this DateTime\n * @param {object} opts - options\n * @param {boolean} opts.suppressMilliseconds - exclude milliseconds from the format if they're 0\n * @param {boolean} opts.supressSeconds - exclude seconds from the format if they're 0\n * @example DateTime.utc(1982, 5, 25).toISO() //=> '1982-05-25T00:00:00.000Z'\n * @example DateTime.local().toISO() //=> '2017-04-22T20:47:05.335-04:00'\n * @return {string}\n */\n toISO({ suppressMilliseconds = false, suppressSeconds = false } = {}) {\n const f = `yyyy-MM-dd'T'${isoTimeFormat(this, suppressSeconds, suppressMilliseconds)}`;\n return formatMaybe(this, f);\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of this DateTime's date component\n * @example DateTime.utc(1982, 5, 25).toISODate() //=> '07:34:19.361Z'\n * @return {string}\n */\n toISODate() {\n return formatMaybe(this, 'yyyy-MM-dd');\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of this DateTime's week date\n * @example DateTime.utc(1982, 5, 25).toISOWeekDate() //=> '1982-W21-2'\n * @return {string}\n */\n toISOWeekDate() {\n return formatMaybe(this, \"kkkk-'W'WW-c\");\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of this DateTime's time component\n * @param {object} opts - options\n * @param {boolean} opts.suppressMilliseconds - exclude milliseconds from the format if they're 0\n * @param {boolean} opts.supressSeconds - exclude seconds from the format if they're 0\n * @example DateTime.utc().hour(7).minute(34).toISOTime() //=> '07:34:19.361Z'\n * @example DateTime.utc().hour(7).minute(34).toISOTime({ suppressSeconds: true }) //=> '07:34Z'\n * @return {string}\n */\n toISOTime({ suppressMilliseconds = false, suppressSeconds = false } = {}) {\n return formatMaybe(this, isoTimeFormat(this, suppressSeconds, suppressMilliseconds));\n }\n\n /**\n * Returns an RFC 2822-compatible string representation of this DateTime, always in UTC\n * @example DateTime.utc(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 +0000'\n * @example DateTime.local(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 -0400'\n * @return {string}\n */\n toRFC2822() {\n return formatMaybe(this, 'EEE, dd LLL yyyy hh:mm:ss ZZZ');\n }\n\n /**\n * Returns a string representation of this DateTime appropriate for use in HTTP headers.\n * Specifically, the string conforms to RFC 1123.\n * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1\n * @example DateTime.utc(2014, 7, 13).toHTTP() //=> 'Sun, 13 Jul 2014 00:00:00 GMT'\n * @return {string}\n */\n toHTTP() {\n return formatMaybe(this.toUTC(), \"EEE, dd LLL yyyy hh:mm:ss 'GMT'\");\n }\n\n /**\n * Returns a string representation of this DateTime appropriate for debugging\n * @return {string}\n */\n toString() {\n return this.isValid ? this.toISO() : INVALID;\n }\n\n /**\n * Returns the epoch milliseconds of this DateTime\n * @return {number}\n */\n valueOf() {\n return this.isValid ? this.ts : NaN;\n }\n\n /**\n * Returns an ISO 8601 representation of this DateTime appropriate for use in JSON.\n * @return {string}\n */\n toJSON() {\n return this.toISO();\n }\n\n /**\n * Returns a Javascript object with this DateTime's year, month, day, and so on.\n * @param opts - options for generating the object\n * @param {boolean} [opts.includeConfig=false] - include configuration attributes in the output\n * @example DateTime.local().toObject() //=> { year: 2017, month: 4, day: 22, hour: 20, minute: 49, second: 42, millisecond: 268 }\n * @return {object}\n */\n toObject(opts = {}) {\n if (!this.isValid) return {};\n\n const base = Object.assign({}, this.c);\n\n if (opts.includeConfig) {\n base.outputCalendar = this.outputCalendar;\n base.numberingSystem = this.loc.numberingSystem;\n base.locale = this.loc.locale;\n }\n return base;\n }\n\n /**\n * Returns a Javascript Date equivalent to this DateTime.\n * @return {object}\n */\n toJSDate() {\n return new Date(this.isValid ? this.ts : NaN);\n }\n\n // COMPARE\n\n /**\n * Return the difference between two DateTimes as a Duration.\n * @param {DateTime} otherDateTime - the DateTime to compare this one to\n * @param {string|string[]} [unit=['milliseconds']] - the unit or array of units (such as 'hours' or 'days') to include in the duration.\n * @param {Object} opts - options that affect the creation of the Duration\n * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use\n * @example\n * var i1 = DateTime.fromISO('1982-05-25T09:45'),\n * i2 = DateTime.fromISO('1983-10-14T10:30');\n * i2.diff(i1).toObject() //=> { milliseconds: 43807500000 }\n * i2.diff(i1, 'hours').toObject() //=> { hours: 12168.75 }\n * i2.diff(i1, ['months', 'days']).toObject() //=> { months: 16, days: 19.03125 }\n * i2.diff(i1, ['months', 'days', 'hours']).toObject() //=> { months: 16, days: 19, hours: 0.75 }\n * @return {Duration}\n */\n diff(otherDateTime, unit = 'milliseconds', opts = {}) {\n if (!this.isValid) return this;\n\n const units = Util.maybeArray(unit).map(Duration.normalizeUnit);\n\n const flipped = otherDateTime.valueOf() > this.valueOf(),\n post = flipped ? otherDateTime : this,\n accum = {};\n\n let cursor = flipped ? this : otherDateTime,\n lowestOrder = null;\n\n if (units.indexOf('years') >= 0) {\n let dYear = post.year - cursor.year;\n\n cursor = cursor.set({ year: post.year });\n\n if (cursor > post) {\n cursor = cursor.minus({ years: 1 });\n dYear -= 1;\n }\n\n accum.years = dYear;\n lowestOrder = 'years';\n }\n\n if (units.indexOf('months') >= 0) {\n const dYear = post.year - cursor.year;\n let dMonth = post.month - cursor.month + dYear * 12;\n\n cursor = cursor.set({ year: post.year, month: post.month });\n\n if (cursor > post) {\n cursor = cursor.minus({ months: 1 });\n dMonth -= 1;\n }\n\n accum.months = dMonth;\n lowestOrder = 'months';\n }\n\n const computeDayDelta = () => {\n const utcDayStart = dt =>\n dt\n .toUTC(0, { keepCalendarTime: true })\n .sta