add.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { addDays } from "./addDays.js";
  2. import { addMonths } from "./addMonths.js";
  3. import { constructFrom } from "./constructFrom.js";
  4. import { toDate } from "./toDate.js";
  5. /**
  6. * The {@link add} function options.
  7. */
  8. /**
  9. * @name add
  10. * @category Common Helpers
  11. * @summary Add the specified years, months, weeks, days, hours, minutes, and seconds to the given date.
  12. *
  13. * @description
  14. * Add the specified years, months, weeks, days, hours, minutes, and seconds to the given date.
  15. *
  16. * @typeParam DateType - The `Date` type the function operates on. Gets inferred from passed arguments. Allows using extensions like [`UTCDate`](https://github.com/date-fns/utc).
  17. * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.
  18. *
  19. * @param date - The date to be changed
  20. * @param duration - The object with years, months, weeks, days, hours, minutes, and seconds to be added.
  21. * @param options - An object with options
  22. *
  23. * @returns The new date with the seconds added
  24. *
  25. * @example
  26. * // Add the following duration to 1 September 2014, 10:19:50
  27. * const result = add(new Date(2014, 8, 1, 10, 19, 50), {
  28. * years: 2,
  29. * months: 9,
  30. * weeks: 1,
  31. * days: 7,
  32. * hours: 5,
  33. * minutes: 9,
  34. * seconds: 30,
  35. * })
  36. * //=> Thu Jun 15 2017 15:29:20
  37. */
  38. export function add(date, duration, options) {
  39. const {
  40. years = 0,
  41. months = 0,
  42. weeks = 0,
  43. days = 0,
  44. hours = 0,
  45. minutes = 0,
  46. seconds = 0,
  47. } = duration;
  48. // Add years and months
  49. const _date = toDate(date, options?.in);
  50. const dateWithMonths =
  51. months || years ? addMonths(_date, months + years * 12) : _date;
  52. // Add weeks and days
  53. const dateWithDays =
  54. days || weeks ? addDays(dateWithMonths, days + weeks * 7) : dateWithMonths;
  55. // Add days, hours, minutes, and seconds
  56. const minutesToAdd = minutes + hours * 60;
  57. const secondsToAdd = seconds + minutesToAdd * 60;
  58. const msToAdd = secondsToAdd * 1000;
  59. return constructFrom(options?.in || date, +dateWithDays + msToAdd);
  60. }
  61. // Fallback for modularized imports:
  62. export default add;