index.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import compareAsc from "../compareAsc/index.js";
  2. import add from "../add/index.js";
  3. import differenceInDays from "../differenceInDays/index.js";
  4. import differenceInHours from "../differenceInHours/index.js";
  5. import differenceInMinutes from "../differenceInMinutes/index.js";
  6. import differenceInMonths from "../differenceInMonths/index.js";
  7. import differenceInSeconds from "../differenceInSeconds/index.js";
  8. import differenceInYears from "../differenceInYears/index.js";
  9. import toDate from "../toDate/index.js";
  10. import requiredArgs from "../_lib/requiredArgs/index.js";
  11. /**
  12. * @name intervalToDuration
  13. * @category Common Helpers
  14. * @summary Convert interval to duration
  15. *
  16. * @description
  17. * Convert a interval object to a duration object.
  18. *
  19. * @param {Interval} interval - the interval to convert to duration
  20. *
  21. * @returns {Duration} The duration Object
  22. * @throws {TypeError} Requires 2 arguments
  23. * @throws {RangeError} `start` must not be Invalid Date
  24. * @throws {RangeError} `end` must not be Invalid Date
  25. *
  26. * @example
  27. * // Get the duration between January 15, 1929 and April 4, 1968.
  28. * intervalToDuration({
  29. * start: new Date(1929, 0, 15, 12, 0, 0),
  30. * end: new Date(1968, 3, 4, 19, 5, 0)
  31. * })
  32. * // => { years: 39, months: 2, days: 20, hours: 7, minutes: 5, seconds: 0 }
  33. */
  34. export default function intervalToDuration(interval) {
  35. requiredArgs(1, arguments);
  36. var start = toDate(interval.start);
  37. var end = toDate(interval.end);
  38. if (isNaN(start.getTime())) throw new RangeError('Start Date is invalid');
  39. if (isNaN(end.getTime())) throw new RangeError('End Date is invalid');
  40. var duration = {};
  41. duration.years = Math.abs(differenceInYears(end, start));
  42. var sign = compareAsc(end, start);
  43. var remainingMonths = add(start, {
  44. years: sign * duration.years
  45. });
  46. duration.months = Math.abs(differenceInMonths(end, remainingMonths));
  47. var remainingDays = add(remainingMonths, {
  48. months: sign * duration.months
  49. });
  50. duration.days = Math.abs(differenceInDays(end, remainingDays));
  51. var remainingHours = add(remainingDays, {
  52. days: sign * duration.days
  53. });
  54. duration.hours = Math.abs(differenceInHours(end, remainingHours));
  55. var remainingMinutes = add(remainingHours, {
  56. hours: sign * duration.hours
  57. });
  58. duration.minutes = Math.abs(differenceInMinutes(end, remainingMinutes));
  59. var remainingSeconds = add(remainingMinutes, {
  60. minutes: sign * duration.minutes
  61. });
  62. duration.seconds = Math.abs(differenceInSeconds(end, remainingSeconds));
  63. return duration;
  64. }