add.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. "use strict";
  2. exports.add = add;
  3. var _index = require("./addDays.js");
  4. var _index2 = require("./addMonths.js");
  5. var _index3 = require("./constructFrom.js");
  6. var _index4 = require("./toDate.js");
  7. /**
  8. * @name add
  9. * @category Common Helpers
  10. * @summary Add the specified years, months, weeks, days, hours, minutes and seconds to the given date.
  11. *
  12. * @description
  13. * Add the specified years, months, weeks, days, hours, minutes and seconds to the given date.
  14. *
  15. * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
  16. *
  17. * @param date - The date to be changed
  18. * @param duration - The object with years, months, weeks, days, hours, minutes and seconds to be added.
  19. *
  20. * | Key | Description |
  21. * |----------------|------------------------------------|
  22. * | years | Amount of years to be added |
  23. * | months | Amount of months to be added |
  24. * | weeks | Amount of weeks to be added |
  25. * | days | Amount of days to be added |
  26. * | hours | Amount of hours to be added |
  27. * | minutes | Amount of minutes to be added |
  28. * | seconds | Amount of seconds to be added |
  29. *
  30. * All values default to 0
  31. *
  32. * @returns The new date with the seconds added
  33. *
  34. * @example
  35. * // Add the following duration to 1 September 2014, 10:19:50
  36. * const result = add(new Date(2014, 8, 1, 10, 19, 50), {
  37. * years: 2,
  38. * months: 9,
  39. * weeks: 1,
  40. * days: 7,
  41. * hours: 5,\\-7
  42. * minutes: 9,
  43. * seconds: 30,
  44. * })
  45. * //=> Thu Jun 15 2017 15:29:20
  46. */
  47. function add(date, duration) {
  48. const {
  49. years = 0,
  50. months = 0,
  51. weeks = 0,
  52. days = 0,
  53. hours = 0,
  54. minutes = 0,
  55. seconds = 0,
  56. } = duration;
  57. // Add years and months
  58. const _date = (0, _index4.toDate)(date);
  59. const dateWithMonths =
  60. months || years
  61. ? (0, _index2.addMonths)(_date, months + years * 12)
  62. : _date;
  63. // Add weeks and days
  64. const dateWithDays =
  65. days || weeks
  66. ? (0, _index.addDays)(dateWithMonths, days + weeks * 7)
  67. : dateWithMonths;
  68. // Add days, hours, minutes and seconds
  69. const minutesToAdd = minutes + hours * 60;
  70. const secondsToAdd = seconds + minutesToAdd * 60;
  71. const msToAdd = secondsToAdd * 1000;
  72. const finalDate = (0, _index3.constructFrom)(
  73. date,
  74. dateWithDays.getTime() + msToAdd,
  75. );
  76. return finalDate;
  77. }