duration.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990
  1. import { InvalidArgumentError, InvalidDurationError, InvalidUnitError } from "./errors.js";
  2. import Formatter from "./impl/formatter.js";
  3. import Invalid from "./impl/invalid.js";
  4. import Locale from "./impl/locale.js";
  5. import { parseISODuration, parseISOTimeOnly } from "./impl/regexParser.js";
  6. import {
  7. asNumber,
  8. hasOwnProperty,
  9. isNumber,
  10. isUndefined,
  11. normalizeObject,
  12. roundTo,
  13. } from "./impl/util.js";
  14. import Settings from "./settings.js";
  15. import DateTime from "./datetime.js";
  16. const INVALID = "Invalid Duration";
  17. // unit conversion constants
  18. export const lowOrderMatrix = {
  19. weeks: {
  20. days: 7,
  21. hours: 7 * 24,
  22. minutes: 7 * 24 * 60,
  23. seconds: 7 * 24 * 60 * 60,
  24. milliseconds: 7 * 24 * 60 * 60 * 1000,
  25. },
  26. days: {
  27. hours: 24,
  28. minutes: 24 * 60,
  29. seconds: 24 * 60 * 60,
  30. milliseconds: 24 * 60 * 60 * 1000,
  31. },
  32. hours: { minutes: 60, seconds: 60 * 60, milliseconds: 60 * 60 * 1000 },
  33. minutes: { seconds: 60, milliseconds: 60 * 1000 },
  34. seconds: { milliseconds: 1000 },
  35. },
  36. casualMatrix = {
  37. years: {
  38. quarters: 4,
  39. months: 12,
  40. weeks: 52,
  41. days: 365,
  42. hours: 365 * 24,
  43. minutes: 365 * 24 * 60,
  44. seconds: 365 * 24 * 60 * 60,
  45. milliseconds: 365 * 24 * 60 * 60 * 1000,
  46. },
  47. quarters: {
  48. months: 3,
  49. weeks: 13,
  50. days: 91,
  51. hours: 91 * 24,
  52. minutes: 91 * 24 * 60,
  53. seconds: 91 * 24 * 60 * 60,
  54. milliseconds: 91 * 24 * 60 * 60 * 1000,
  55. },
  56. months: {
  57. weeks: 4,
  58. days: 30,
  59. hours: 30 * 24,
  60. minutes: 30 * 24 * 60,
  61. seconds: 30 * 24 * 60 * 60,
  62. milliseconds: 30 * 24 * 60 * 60 * 1000,
  63. },
  64. ...lowOrderMatrix,
  65. },
  66. daysInYearAccurate = 146097.0 / 400,
  67. daysInMonthAccurate = 146097.0 / 4800,
  68. accurateMatrix = {
  69. years: {
  70. quarters: 4,
  71. months: 12,
  72. weeks: daysInYearAccurate / 7,
  73. days: daysInYearAccurate,
  74. hours: daysInYearAccurate * 24,
  75. minutes: daysInYearAccurate * 24 * 60,
  76. seconds: daysInYearAccurate * 24 * 60 * 60,
  77. milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1000,
  78. },
  79. quarters: {
  80. months: 3,
  81. weeks: daysInYearAccurate / 28,
  82. days: daysInYearAccurate / 4,
  83. hours: (daysInYearAccurate * 24) / 4,
  84. minutes: (daysInYearAccurate * 24 * 60) / 4,
  85. seconds: (daysInYearAccurate * 24 * 60 * 60) / 4,
  86. milliseconds: (daysInYearAccurate * 24 * 60 * 60 * 1000) / 4,
  87. },
  88. months: {
  89. weeks: daysInMonthAccurate / 7,
  90. days: daysInMonthAccurate,
  91. hours: daysInMonthAccurate * 24,
  92. minutes: daysInMonthAccurate * 24 * 60,
  93. seconds: daysInMonthAccurate * 24 * 60 * 60,
  94. milliseconds: daysInMonthAccurate * 24 * 60 * 60 * 1000,
  95. },
  96. ...lowOrderMatrix,
  97. };
  98. // units ordered by size
  99. const orderedUnits = [
  100. "years",
  101. "quarters",
  102. "months",
  103. "weeks",
  104. "days",
  105. "hours",
  106. "minutes",
  107. "seconds",
  108. "milliseconds",
  109. ];
  110. const reverseUnits = orderedUnits.slice(0).reverse();
  111. // clone really means "create another instance just like this one, but with these changes"
  112. function clone(dur, alts, clear = false) {
  113. // deep merge for vals
  114. const conf = {
  115. values: clear ? alts.values : { ...dur.values, ...(alts.values || {}) },
  116. loc: dur.loc.clone(alts.loc),
  117. conversionAccuracy: alts.conversionAccuracy || dur.conversionAccuracy,
  118. matrix: alts.matrix || dur.matrix,
  119. };
  120. return new Duration(conf);
  121. }
  122. function durationToMillis(matrix, vals) {
  123. let sum = vals.milliseconds ?? 0;
  124. for (const unit of reverseUnits.slice(1)) {
  125. if (vals[unit]) {
  126. sum += vals[unit] * matrix[unit]["milliseconds"];
  127. }
  128. }
  129. return sum;
  130. }
  131. // NB: mutates parameters
  132. function normalizeValues(matrix, vals) {
  133. // the logic below assumes the overall value of the duration is positive
  134. // if this is not the case, factor is used to make it so
  135. const factor = durationToMillis(matrix, vals) < 0 ? -1 : 1;
  136. orderedUnits.reduceRight((previous, current) => {
  137. if (!isUndefined(vals[current])) {
  138. if (previous) {
  139. const previousVal = vals[previous] * factor;
  140. const conv = matrix[current][previous];
  141. // if (previousVal < 0):
  142. // lower order unit is negative (e.g. { years: 2, days: -2 })
  143. // normalize this by reducing the higher order unit by the appropriate amount
  144. // and increasing the lower order unit
  145. // this can never make the higher order unit negative, because this function only operates
  146. // on positive durations, so the amount of time represented by the lower order unit cannot
  147. // be larger than the higher order unit
  148. // else:
  149. // lower order unit is positive (e.g. { years: 2, days: 450 } or { years: -2, days: 450 })
  150. // in this case we attempt to convert as much as possible from the lower order unit into
  151. // the higher order one
  152. //
  153. // Math.floor takes care of both of these cases, rounding away from 0
  154. // if previousVal < 0 it makes the absolute value larger
  155. // if previousVal >= it makes the absolute value smaller
  156. const rollUp = Math.floor(previousVal / conv);
  157. vals[current] += rollUp * factor;
  158. vals[previous] -= rollUp * conv * factor;
  159. }
  160. return current;
  161. } else {
  162. return previous;
  163. }
  164. }, null);
  165. // try to convert any decimals into smaller units if possible
  166. // for example for { years: 2.5, days: 0, seconds: 0 } we want to get { years: 2, days: 182, hours: 12 }
  167. orderedUnits.reduce((previous, current) => {
  168. if (!isUndefined(vals[current])) {
  169. if (previous) {
  170. const fraction = vals[previous] % 1;
  171. vals[previous] -= fraction;
  172. vals[current] += fraction * matrix[previous][current];
  173. }
  174. return current;
  175. } else {
  176. return previous;
  177. }
  178. }, null);
  179. }
  180. // Remove all properties with a value of 0 from an object
  181. function removeZeroes(vals) {
  182. const newVals = {};
  183. for (const [key, value] of Object.entries(vals)) {
  184. if (value !== 0) {
  185. newVals[key] = value;
  186. }
  187. }
  188. return newVals;
  189. }
  190. /**
  191. * A Duration object represents a period of time, like "2 months" or "1 day, 1 hour". Conceptually, it's just a map of units to their quantities, accompanied by some additional configuration and methods for creating, parsing, interrogating, transforming, and formatting them. They can be used on their own or in conjunction with other Luxon types; for example, you can use {@link DateTime#plus} to add a Duration object to a DateTime, producing another DateTime.
  192. *
  193. * Here is a brief overview of commonly used methods and getters in Duration:
  194. *
  195. * * **Creation** To create a Duration, use {@link Duration.fromMillis}, {@link Duration.fromObject}, or {@link Duration.fromISO}.
  196. * * **Unit values** See the {@link Duration#years}, {@link Duration#months}, {@link Duration#weeks}, {@link Duration#days}, {@link Duration#hours}, {@link Duration#minutes}, {@link Duration#seconds}, {@link Duration#milliseconds} accessors.
  197. * * **Configuration** See {@link Duration#locale} and {@link Duration#numberingSystem} accessors.
  198. * * **Transformation** To create new Durations out of old ones use {@link Duration#plus}, {@link Duration#minus}, {@link Duration#normalize}, {@link Duration#set}, {@link Duration#reconfigure}, {@link Duration#shiftTo}, and {@link Duration#negate}.
  199. * * **Output** To convert the Duration into other representations, see {@link Duration#as}, {@link Duration#toISO}, {@link Duration#toFormat}, and {@link Duration#toJSON}
  200. *
  201. * There's are more methods documented below. In addition, for more information on subtler topics like internationalization and validity, see the external documentation.
  202. */
  203. export default class Duration {
  204. /**
  205. * @private
  206. */
  207. constructor(config) {
  208. const accurate = config.conversionAccuracy === "longterm" || false;
  209. let matrix = accurate ? accurateMatrix : casualMatrix;
  210. if (config.matrix) {
  211. matrix = config.matrix;
  212. }
  213. /**
  214. * @access private
  215. */
  216. this.values = config.values;
  217. /**
  218. * @access private
  219. */
  220. this.loc = config.loc || Locale.create();
  221. /**
  222. * @access private
  223. */
  224. this.conversionAccuracy = accurate ? "longterm" : "casual";
  225. /**
  226. * @access private
  227. */
  228. this.invalid = config.invalid || null;
  229. /**
  230. * @access private
  231. */
  232. this.matrix = matrix;
  233. /**
  234. * @access private
  235. */
  236. this.isLuxonDuration = true;
  237. }
  238. /**
  239. * Create Duration from a number of milliseconds.
  240. * @param {number} count of milliseconds
  241. * @param {Object} opts - options for parsing
  242. * @param {string} [opts.locale='en-US'] - the locale to use
  243. * @param {string} opts.numberingSystem - the numbering system to use
  244. * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
  245. * @return {Duration}
  246. */
  247. static fromMillis(count, opts) {
  248. return Duration.fromObject({ milliseconds: count }, opts);
  249. }
  250. /**
  251. * Create a Duration from a JavaScript object with keys like 'years' and 'hours'.
  252. * If this object is empty then a zero milliseconds duration is returned.
  253. * @param {Object} obj - the object to create the DateTime from
  254. * @param {number} obj.years
  255. * @param {number} obj.quarters
  256. * @param {number} obj.months
  257. * @param {number} obj.weeks
  258. * @param {number} obj.days
  259. * @param {number} obj.hours
  260. * @param {number} obj.minutes
  261. * @param {number} obj.seconds
  262. * @param {number} obj.milliseconds
  263. * @param {Object} [opts=[]] - options for creating this Duration
  264. * @param {string} [opts.locale='en-US'] - the locale to use
  265. * @param {string} opts.numberingSystem - the numbering system to use
  266. * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use
  267. * @param {string} [opts.matrix=Object] - the custom conversion system to use
  268. * @return {Duration}
  269. */
  270. static fromObject(obj, opts = {}) {
  271. if (obj == null || typeof obj !== "object") {
  272. throw new InvalidArgumentError(
  273. `Duration.fromObject: argument expected to be an object, got ${
  274. obj === null ? "null" : typeof obj
  275. }`
  276. );
  277. }
  278. return new Duration({
  279. values: normalizeObject(obj, Duration.normalizeUnit),
  280. loc: Locale.fromObject(opts),
  281. conversionAccuracy: opts.conversionAccuracy,
  282. matrix: opts.matrix,
  283. });
  284. }
  285. /**
  286. * Create a Duration from DurationLike.
  287. *
  288. * @param {Object | number | Duration} durationLike
  289. * One of:
  290. * - object with keys like 'years' and 'hours'.
  291. * - number representing milliseconds
  292. * - Duration instance
  293. * @return {Duration}
  294. */
  295. static fromDurationLike(durationLike) {
  296. if (isNumber(durationLike)) {
  297. return Duration.fromMillis(durationLike);
  298. } else if (Duration.isDuration(durationLike)) {
  299. return durationLike;
  300. } else if (typeof durationLike === "object") {
  301. return Duration.fromObject(durationLike);
  302. } else {
  303. throw new InvalidArgumentError(
  304. `Unknown duration argument ${durationLike} of type ${typeof durationLike}`
  305. );
  306. }
  307. }
  308. /**
  309. * Create a Duration from an ISO 8601 duration string.
  310. * @param {string} text - text to parse
  311. * @param {Object} opts - options for parsing
  312. * @param {string} [opts.locale='en-US'] - the locale to use
  313. * @param {string} opts.numberingSystem - the numbering system to use
  314. * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use
  315. * @param {string} [opts.matrix=Object] - the preset conversion system to use
  316. * @see https://en.wikipedia.org/wiki/ISO_8601#Durations
  317. * @example Duration.fromISO('P3Y6M1W4DT12H30M5S').toObject() //=> { years: 3, months: 6, weeks: 1, days: 4, hours: 12, minutes: 30, seconds: 5 }
  318. * @example Duration.fromISO('PT23H').toObject() //=> { hours: 23 }
  319. * @example Duration.fromISO('P5Y3M').toObject() //=> { years: 5, months: 3 }
  320. * @return {Duration}
  321. */
  322. static fromISO(text, opts) {
  323. const [parsed] = parseISODuration(text);
  324. if (parsed) {
  325. return Duration.fromObject(parsed, opts);
  326. } else {
  327. return Duration.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`);
  328. }
  329. }
  330. /**
  331. * Create a Duration from an ISO 8601 time string.
  332. * @param {string} text - text to parse
  333. * @param {Object} opts - options for parsing
  334. * @param {string} [opts.locale='en-US'] - the locale to use
  335. * @param {string} opts.numberingSystem - the numbering system to use
  336. * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use
  337. * @param {string} [opts.matrix=Object] - the conversion system to use
  338. * @see https://en.wikipedia.org/wiki/ISO_8601#Times
  339. * @example Duration.fromISOTime('11:22:33.444').toObject() //=> { hours: 11, minutes: 22, seconds: 33, milliseconds: 444 }
  340. * @example Duration.fromISOTime('11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
  341. * @example Duration.fromISOTime('T11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
  342. * @example Duration.fromISOTime('1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
  343. * @example Duration.fromISOTime('T1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
  344. * @return {Duration}
  345. */
  346. static fromISOTime(text, opts) {
  347. const [parsed] = parseISOTimeOnly(text);
  348. if (parsed) {
  349. return Duration.fromObject(parsed, opts);
  350. } else {
  351. return Duration.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`);
  352. }
  353. }
  354. /**
  355. * Create an invalid Duration.
  356. * @param {string} reason - simple string of why this datetime is invalid. Should not contain parameters or anything else data-dependent
  357. * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information
  358. * @return {Duration}
  359. */
  360. static invalid(reason, explanation = null) {
  361. if (!reason) {
  362. throw new InvalidArgumentError("need to specify a reason the Duration is invalid");
  363. }
  364. const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
  365. if (Settings.throwOnInvalid) {
  366. throw new InvalidDurationError(invalid);
  367. } else {
  368. return new Duration({ invalid });
  369. }
  370. }
  371. /**
  372. * @private
  373. */
  374. static normalizeUnit(unit) {
  375. const normalized = {
  376. year: "years",
  377. years: "years",
  378. quarter: "quarters",
  379. quarters: "quarters",
  380. month: "months",
  381. months: "months",
  382. week: "weeks",
  383. weeks: "weeks",
  384. day: "days",
  385. days: "days",
  386. hour: "hours",
  387. hours: "hours",
  388. minute: "minutes",
  389. minutes: "minutes",
  390. second: "seconds",
  391. seconds: "seconds",
  392. millisecond: "milliseconds",
  393. milliseconds: "milliseconds",
  394. }[unit ? unit.toLowerCase() : unit];
  395. if (!normalized) throw new InvalidUnitError(unit);
  396. return normalized;
  397. }
  398. /**
  399. * Check if an object is a Duration. Works across context boundaries
  400. * @param {object} o
  401. * @return {boolean}
  402. */
  403. static isDuration(o) {
  404. return (o && o.isLuxonDuration) || false;
  405. }
  406. /**
  407. * Get the locale of a Duration, such 'en-GB'
  408. * @type {string}
  409. */
  410. get locale() {
  411. return this.isValid ? this.loc.locale : null;
  412. }
  413. /**
  414. * Get the numbering system of a Duration, such 'beng'. The numbering system is used when formatting the Duration
  415. *
  416. * @type {string}
  417. */
  418. get numberingSystem() {
  419. return this.isValid ? this.loc.numberingSystem : null;
  420. }
  421. /**
  422. * Returns a string representation of this Duration formatted according to the specified format string. You may use these tokens:
  423. * * `S` for milliseconds
  424. * * `s` for seconds
  425. * * `m` for minutes
  426. * * `h` for hours
  427. * * `d` for days
  428. * * `w` for weeks
  429. * * `M` for months
  430. * * `y` for years
  431. * Notes:
  432. * * Add padding by repeating the token, e.g. "yy" pads the years to two digits, "hhhh" pads the hours out to four digits
  433. * * Tokens can be escaped by wrapping with single quotes.
  434. * * The duration will be converted to the set of units in the format string using {@link Duration#shiftTo} and the Durations's conversion accuracy setting.
  435. * @param {string} fmt - the format string
  436. * @param {Object} opts - options
  437. * @param {boolean} [opts.floor=true] - floor numerical values
  438. * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("y d s") //=> "1 6 2"
  439. * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("yy dd sss") //=> "01 06 002"
  440. * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("M S") //=> "12 518402000"
  441. * @return {string}
  442. */
  443. toFormat(fmt, opts = {}) {
  444. // reverse-compat since 1.2; we always round down now, never up, and we do it by default
  445. const fmtOpts = {
  446. ...opts,
  447. floor: opts.round !== false && opts.floor !== false,
  448. };
  449. return this.isValid
  450. ? Formatter.create(this.loc, fmtOpts).formatDurationFromString(this, fmt)
  451. : INVALID;
  452. }
  453. /**
  454. * Returns a string representation of a Duration with all units included.
  455. * To modify its behavior, use `listStyle` and any Intl.NumberFormat option, though `unitDisplay` is especially relevant.
  456. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options
  457. * @param {Object} opts - Formatting options. Accepts the same keys as the options parameter of the native `Intl.NumberFormat` constructor, as well as `listStyle`.
  458. * @param {string} [opts.listStyle='narrow'] - How to format the merged list. Corresponds to the `style` property of the options parameter of the native `Intl.ListFormat` constructor.
  459. * @example
  460. * ```js
  461. * var dur = Duration.fromObject({ days: 1, hours: 5, minutes: 6 })
  462. * dur.toHuman() //=> '1 day, 5 hours, 6 minutes'
  463. * dur.toHuman({ listStyle: "long" }) //=> '1 day, 5 hours, and 6 minutes'
  464. * dur.toHuman({ unitDisplay: "short" }) //=> '1 day, 5 hr, 6 min'
  465. * ```
  466. */
  467. toHuman(opts = {}) {
  468. if (!this.isValid) return INVALID;
  469. const l = orderedUnits
  470. .map((unit) => {
  471. const val = this.values[unit];
  472. if (isUndefined(val)) {
  473. return null;
  474. }
  475. return this.loc
  476. .numberFormatter({ style: "unit", unitDisplay: "long", ...opts, unit: unit.slice(0, -1) })
  477. .format(val);
  478. })
  479. .filter((n) => n);
  480. return this.loc
  481. .listFormatter({ type: "conjunction", style: opts.listStyle || "narrow", ...opts })
  482. .format(l);
  483. }
  484. /**
  485. * Returns a JavaScript object with this Duration's values.
  486. * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toObject() //=> { years: 1, days: 6, seconds: 2 }
  487. * @return {Object}
  488. */
  489. toObject() {
  490. if (!this.isValid) return {};
  491. return { ...this.values };
  492. }
  493. /**
  494. * Returns an ISO 8601-compliant string representation of this Duration.
  495. * @see https://en.wikipedia.org/wiki/ISO_8601#Durations
  496. * @example Duration.fromObject({ years: 3, seconds: 45 }).toISO() //=> 'P3YT45S'
  497. * @example Duration.fromObject({ months: 4, seconds: 45 }).toISO() //=> 'P4MT45S'
  498. * @example Duration.fromObject({ months: 5 }).toISO() //=> 'P5M'
  499. * @example Duration.fromObject({ minutes: 5 }).toISO() //=> 'PT5M'
  500. * @example Duration.fromObject({ milliseconds: 6 }).toISO() //=> 'PT0.006S'
  501. * @return {string}
  502. */
  503. toISO() {
  504. // we could use the formatter, but this is an easier way to get the minimum string
  505. if (!this.isValid) return null;
  506. let s = "P";
  507. if (this.years !== 0) s += this.years + "Y";
  508. if (this.months !== 0 || this.quarters !== 0) s += this.months + this.quarters * 3 + "M";
  509. if (this.weeks !== 0) s += this.weeks + "W";
  510. if (this.days !== 0) s += this.days + "D";
  511. if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0)
  512. s += "T";
  513. if (this.hours !== 0) s += this.hours + "H";
  514. if (this.minutes !== 0) s += this.minutes + "M";
  515. if (this.seconds !== 0 || this.milliseconds !== 0)
  516. // this will handle "floating point madness" by removing extra decimal places
  517. // https://stackoverflow.com/questions/588004/is-floating-point-math-broken
  518. s += roundTo(this.seconds + this.milliseconds / 1000, 3) + "S";
  519. if (s === "P") s += "T0S";
  520. return s;
  521. }
  522. /**
  523. * Returns an ISO 8601-compliant string representation of this Duration, formatted as a time of day.
  524. * Note that this will return null if the duration is invalid, negative, or equal to or greater than 24 hours.
  525. * @see https://en.wikipedia.org/wiki/ISO_8601#Times
  526. * @param {Object} opts - options
  527. * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0
  528. * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0
  529. * @param {boolean} [opts.includePrefix=false] - include the `T` prefix
  530. * @param {string} [opts.format='extended'] - choose between the basic and extended format
  531. * @example Duration.fromObject({ hours: 11 }).toISOTime() //=> '11:00:00.000'
  532. * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressMilliseconds: true }) //=> '11:00:00'
  533. * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressSeconds: true }) //=> '11:00'
  534. * @example Duration.fromObject({ hours: 11 }).toISOTime({ includePrefix: true }) //=> 'T11:00:00.000'
  535. * @example Duration.fromObject({ hours: 11 }).toISOTime({ format: 'basic' }) //=> '110000.000'
  536. * @return {string}
  537. */
  538. toISOTime(opts = {}) {
  539. if (!this.isValid) return null;
  540. const millis = this.toMillis();
  541. if (millis < 0 || millis >= 86400000) return null;
  542. opts = {
  543. suppressMilliseconds: false,
  544. suppressSeconds: false,
  545. includePrefix: false,
  546. format: "extended",
  547. ...opts,
  548. includeOffset: false,
  549. };
  550. const dateTime = DateTime.fromMillis(millis, { zone: "UTC" });
  551. return dateTime.toISOTime(opts);
  552. }
  553. /**
  554. * Returns an ISO 8601 representation of this Duration appropriate for use in JSON.
  555. * @return {string}
  556. */
  557. toJSON() {
  558. return this.toISO();
  559. }
  560. /**
  561. * Returns an ISO 8601 representation of this Duration appropriate for use in debugging.
  562. * @return {string}
  563. */
  564. toString() {
  565. return this.toISO();
  566. }
  567. /**
  568. * Returns a string representation of this Duration appropriate for the REPL.
  569. * @return {string}
  570. */
  571. [Symbol.for("nodejs.util.inspect.custom")]() {
  572. if (this.isValid) {
  573. return `Duration { values: ${JSON.stringify(this.values)} }`;
  574. } else {
  575. return `Duration { Invalid, reason: ${this.invalidReason} }`;
  576. }
  577. }
  578. /**
  579. * Returns an milliseconds value of this Duration.
  580. * @return {number}
  581. */
  582. toMillis() {
  583. if (!this.isValid) return NaN;
  584. return durationToMillis(this.matrix, this.values);
  585. }
  586. /**
  587. * Returns an milliseconds value of this Duration. Alias of {@link toMillis}
  588. * @return {number}
  589. */
  590. valueOf() {
  591. return this.toMillis();
  592. }
  593. /**
  594. * Make this Duration longer by the specified amount. Return a newly-constructed Duration.
  595. * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
  596. * @return {Duration}
  597. */
  598. plus(duration) {
  599. if (!this.isValid) return this;
  600. const dur = Duration.fromDurationLike(duration),
  601. result = {};
  602. for (const k of orderedUnits) {
  603. if (hasOwnProperty(dur.values, k) || hasOwnProperty(this.values, k)) {
  604. result[k] = dur.get(k) + this.get(k);
  605. }
  606. }
  607. return clone(this, { values: result }, true);
  608. }
  609. /**
  610. * Make this Duration shorter by the specified amount. Return a newly-constructed Duration.
  611. * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
  612. * @return {Duration}
  613. */
  614. minus(duration) {
  615. if (!this.isValid) return this;
  616. const dur = Duration.fromDurationLike(duration);
  617. return this.plus(dur.negate());
  618. }
  619. /**
  620. * Scale this Duration by the specified amount. Return a newly-constructed Duration.
  621. * @param {function} fn - The function to apply to each unit. Arity is 1 or 2: the value of the unit and, optionally, the unit name. Must return a number.
  622. * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits(x => x * 2) //=> { hours: 2, minutes: 60 }
  623. * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits((x, u) => u === "hours" ? x * 2 : x) //=> { hours: 2, minutes: 30 }
  624. * @return {Duration}
  625. */
  626. mapUnits(fn) {
  627. if (!this.isValid) return this;
  628. const result = {};
  629. for (const k of Object.keys(this.values)) {
  630. result[k] = asNumber(fn(this.values[k], k));
  631. }
  632. return clone(this, { values: result }, true);
  633. }
  634. /**
  635. * Get the value of unit.
  636. * @param {string} unit - a unit such as 'minute' or 'day'
  637. * @example Duration.fromObject({years: 2, days: 3}).get('years') //=> 2
  638. * @example Duration.fromObject({years: 2, days: 3}).get('months') //=> 0
  639. * @example Duration.fromObject({years: 2, days: 3}).get('days') //=> 3
  640. * @return {number}
  641. */
  642. get(unit) {
  643. return this[Duration.normalizeUnit(unit)];
  644. }
  645. /**
  646. * "Set" the values of specified units. Return a newly-constructed Duration.
  647. * @param {Object} values - a mapping of units to numbers
  648. * @example dur.set({ years: 2017 })
  649. * @example dur.set({ hours: 8, minutes: 30 })
  650. * @return {Duration}
  651. */
  652. set(values) {
  653. if (!this.isValid) return this;
  654. const mixed = { ...this.values, ...normalizeObject(values, Duration.normalizeUnit) };
  655. return clone(this, { values: mixed });
  656. }
  657. /**
  658. * "Set" the locale and/or numberingSystem. Returns a newly-constructed Duration.
  659. * @example dur.reconfigure({ locale: 'en-GB' })
  660. * @return {Duration}
  661. */
  662. reconfigure({ locale, numberingSystem, conversionAccuracy, matrix } = {}) {
  663. const loc = this.loc.clone({ locale, numberingSystem });
  664. const opts = { loc, matrix, conversionAccuracy };
  665. return clone(this, opts);
  666. }
  667. /**
  668. * Return the length of the duration in the specified unit.
  669. * @param {string} unit - a unit such as 'minutes' or 'days'
  670. * @example Duration.fromObject({years: 1}).as('days') //=> 365
  671. * @example Duration.fromObject({years: 1}).as('months') //=> 12
  672. * @example Duration.fromObject({hours: 60}).as('days') //=> 2.5
  673. * @return {number}
  674. */
  675. as(unit) {
  676. return this.isValid ? this.shiftTo(unit).get(unit) : NaN;
  677. }
  678. /**
  679. * Reduce this Duration to its canonical representation in its current units.
  680. * Assuming the overall value of the Duration is positive, this means:
  681. * - excessive values for lower-order units are converted to higher-order units (if possible, see first and second example)
  682. * - negative lower-order units are converted to higher order units (there must be such a higher order unit, otherwise
  683. * the overall value would be negative, see third example)
  684. * - fractional values for higher-order units are converted to lower-order units (if possible, see fourth example)
  685. *
  686. * If the overall value is negative, the result of this method is equivalent to `this.negate().normalize().negate()`.
  687. * @example Duration.fromObject({ years: 2, days: 5000 }).normalize().toObject() //=> { years: 15, days: 255 }
  688. * @example Duration.fromObject({ days: 5000 }).normalize().toObject() //=> { days: 5000 }
  689. * @example Duration.fromObject({ hours: 12, minutes: -45 }).normalize().toObject() //=> { hours: 11, minutes: 15 }
  690. * @example Duration.fromObject({ years: 2.5, days: 0, hours: 0 }).normalize().toObject() //=> { years: 2, days: 182, hours: 12 }
  691. * @return {Duration}
  692. */
  693. normalize() {
  694. if (!this.isValid) return this;
  695. const vals = this.toObject();
  696. normalizeValues(this.matrix, vals);
  697. return clone(this, { values: vals }, true);
  698. }
  699. /**
  700. * Rescale units to its largest representation
  701. * @example Duration.fromObject({ milliseconds: 90000 }).rescale().toObject() //=> { minutes: 1, seconds: 30 }
  702. * @return {Duration}
  703. */
  704. rescale() {
  705. if (!this.isValid) return this;
  706. const vals = removeZeroes(this.normalize().shiftToAll().toObject());
  707. return clone(this, { values: vals }, true);
  708. }
  709. /**
  710. * Convert this Duration into its representation in a different set of units.
  711. * @example Duration.fromObject({ hours: 1, seconds: 30 }).shiftTo('minutes', 'milliseconds').toObject() //=> { minutes: 60, milliseconds: 30000 }
  712. * @return {Duration}
  713. */
  714. shiftTo(...units) {
  715. if (!this.isValid) return this;
  716. if (units.length === 0) {
  717. return this;
  718. }
  719. units = units.map((u) => Duration.normalizeUnit(u));
  720. const built = {},
  721. accumulated = {},
  722. vals = this.toObject();
  723. let lastUnit;
  724. for (const k of orderedUnits) {
  725. if (units.indexOf(k) >= 0) {
  726. lastUnit = k;
  727. let own = 0;
  728. // anything we haven't boiled down yet should get boiled to this unit
  729. for (const ak in accumulated) {
  730. own += this.matrix[ak][k] * accumulated[ak];
  731. accumulated[ak] = 0;
  732. }
  733. // plus anything that's already in this unit
  734. if (isNumber(vals[k])) {
  735. own += vals[k];
  736. }
  737. // only keep the integer part for now in the hopes of putting any decimal part
  738. // into a smaller unit later
  739. const i = Math.trunc(own);
  740. built[k] = i;
  741. accumulated[k] = (own * 1000 - i * 1000) / 1000;
  742. // otherwise, keep it in the wings to boil it later
  743. } else if (isNumber(vals[k])) {
  744. accumulated[k] = vals[k];
  745. }
  746. }
  747. // anything leftover becomes the decimal for the last unit
  748. // lastUnit must be defined since units is not empty
  749. for (const key in accumulated) {
  750. if (accumulated[key] !== 0) {
  751. built[lastUnit] +=
  752. key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key];
  753. }
  754. }
  755. normalizeValues(this.matrix, built);
  756. return clone(this, { values: built }, true);
  757. }
  758. /**
  759. * Shift this Duration to all available units.
  760. * Same as shiftTo("years", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds")
  761. * @return {Duration}
  762. */
  763. shiftToAll() {
  764. if (!this.isValid) return this;
  765. return this.shiftTo(
  766. "years",
  767. "months",
  768. "weeks",
  769. "days",
  770. "hours",
  771. "minutes",
  772. "seconds",
  773. "milliseconds"
  774. );
  775. }
  776. /**
  777. * Return the negative of this Duration.
  778. * @example Duration.fromObject({ hours: 1, seconds: 30 }).negate().toObject() //=> { hours: -1, seconds: -30 }
  779. * @return {Duration}
  780. */
  781. negate() {
  782. if (!this.isValid) return this;
  783. const negated = {};
  784. for (const k of Object.keys(this.values)) {
  785. negated[k] = this.values[k] === 0 ? 0 : -this.values[k];
  786. }
  787. return clone(this, { values: negated }, true);
  788. }
  789. /**
  790. * Get the years.
  791. * @type {number}
  792. */
  793. get years() {
  794. return this.isValid ? this.values.years || 0 : NaN;
  795. }
  796. /**
  797. * Get the quarters.
  798. * @type {number}
  799. */
  800. get quarters() {
  801. return this.isValid ? this.values.quarters || 0 : NaN;
  802. }
  803. /**
  804. * Get the months.
  805. * @type {number}
  806. */
  807. get months() {
  808. return this.isValid ? this.values.months || 0 : NaN;
  809. }
  810. /**
  811. * Get the weeks
  812. * @type {number}
  813. */
  814. get weeks() {
  815. return this.isValid ? this.values.weeks || 0 : NaN;
  816. }
  817. /**
  818. * Get the days.
  819. * @type {number}
  820. */
  821. get days() {
  822. return this.isValid ? this.values.days || 0 : NaN;
  823. }
  824. /**
  825. * Get the hours.
  826. * @type {number}
  827. */
  828. get hours() {
  829. return this.isValid ? this.values.hours || 0 : NaN;
  830. }
  831. /**
  832. * Get the minutes.
  833. * @type {number}
  834. */
  835. get minutes() {
  836. return this.isValid ? this.values.minutes || 0 : NaN;
  837. }
  838. /**
  839. * Get the seconds.
  840. * @return {number}
  841. */
  842. get seconds() {
  843. return this.isValid ? this.values.seconds || 0 : NaN;
  844. }
  845. /**
  846. * Get the milliseconds.
  847. * @return {number}
  848. */
  849. get milliseconds() {
  850. return this.isValid ? this.values.milliseconds || 0 : NaN;
  851. }
  852. /**
  853. * Returns whether the Duration is invalid. Invalid durations are returned by diff operations
  854. * on invalid DateTimes or Intervals.
  855. * @return {boolean}
  856. */
  857. get isValid() {
  858. return this.invalid === null;
  859. }
  860. /**
  861. * Returns an error code if this Duration became invalid, or null if the Duration is valid
  862. * @return {string}
  863. */
  864. get invalidReason() {
  865. return this.invalid ? this.invalid.reason : null;
  866. }
  867. /**
  868. * Returns an explanation of why this Duration became invalid, or null if the Duration is valid
  869. * @type {string}
  870. */
  871. get invalidExplanation() {
  872. return this.invalid ? this.invalid.explanation : null;
  873. }
  874. /**
  875. * Equality check
  876. * Two Durations are equal iff they have the same units and the same values for each unit.
  877. * @param {Duration} other
  878. * @return {boolean}
  879. */
  880. equals(other) {
  881. if (!this.isValid || !other.isValid) {
  882. return false;
  883. }
  884. if (!this.loc.equals(other.loc)) {
  885. return false;
  886. }
  887. function eq(v1, v2) {
  888. // Consider 0 and undefined as equal
  889. if (v1 === undefined || v1 === 0) return v2 === undefined || v2 === 0;
  890. return v1 === v2;
  891. }
  892. for (const u of orderedUnits) {
  893. if (!eq(this.values[u], other.values[u])) {
  894. return false;
  895. }
  896. }
  897. return true;
  898. }
  899. }