duration.js 29 KB

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