add.mjs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { addDays } from "./addDays.mjs";
  2. import { addMonths } from "./addMonths.mjs";
  3. import { constructFrom } from "./constructFrom.mjs";
  4. import { toDate } from "./toDate.mjs";
  5. /**
  6. * @name add
  7. * @category Common Helpers
  8. * @summary Add the specified years, months, weeks, days, hours, minutes and seconds to the given date.
  9. *
  10. * @description
  11. * Add the specified years, months, weeks, days, hours, minutes and seconds to the given date.
  12. *
  13. * @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).
  14. *
  15. * @param date - The date to be changed
  16. * @param duration - The object with years, months, weeks, days, hours, minutes and seconds to be added.
  17. *
  18. * | Key | Description |
  19. * |----------------|------------------------------------|
  20. * | years | Amount of years to be added |
  21. * | months | Amount of months to be added |
  22. * | weeks | Amount of weeks to be added |
  23. * | days | Amount of days to be added |
  24. * | hours | Amount of hours to be added |
  25. * | minutes | Amount of minutes to be added |
  26. * | seconds | Amount of seconds to be added |
  27. *
  28. * All values default to 0
  29. *
  30. * @returns The new date with the seconds added
  31. *
  32. * @example
  33. * // Add the following duration to 1 September 2014, 10:19:50
  34. * const result = add(new Date(2014, 8, 1, 10, 19, 50), {
  35. * years: 2,
  36. * months: 9,
  37. * weeks: 1,
  38. * days: 7,
  39. * hours: 5,\\-7
  40. * minutes: 9,
  41. * seconds: 30,
  42. * })
  43. * //=> Thu Jun 15 2017 15:29:20
  44. */
  45. export function add(date, duration) {
  46. const {
  47. years = 0,
  48. months = 0,
  49. weeks = 0,
  50. days = 0,
  51. hours = 0,
  52. minutes = 0,
  53. seconds = 0,
  54. } = duration;
  55. // Add years and months
  56. const _date = toDate(date);
  57. const dateWithMonths =
  58. months || years ? addMonths(_date, months + years * 12) : _date;
  59. // Add weeks and days
  60. const dateWithDays =
  61. days || weeks ? addDays(dateWithMonths, days + weeks * 7) : dateWithMonths;
  62. // Add days, hours, minutes and seconds
  63. const minutesToAdd = minutes + hours * 60;
  64. const secondsToAdd = seconds + minutesToAdd * 60;
  65. const msToAdd = secondsToAdd * 1000;
  66. const finalDate = constructFrom(date, dateWithDays.getTime() + msToAdd);
  67. return finalDate;
  68. }
  69. // Fallback for modularized imports:
  70. export default add;