add.cjs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. "use strict";
  2. exports.add = add;
  3. var _index = require("./addDays.cjs");
  4. var _index2 = require("./addMonths.cjs");
  5. var _index3 = require("./constructFrom.cjs");
  6. var _index4 = require("./toDate.cjs");
  7. /**
  8. * The {@link add} function options.
  9. */
  10. /**
  11. * @name add
  12. * @category Common Helpers
  13. * @summary Add the specified years, months, weeks, days, hours, minutes, and seconds to the given date.
  14. *
  15. * @description
  16. * Add the specified years, months, weeks, days, hours, minutes, and seconds to the given date.
  17. *
  18. * @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).
  19. * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.
  20. *
  21. * @param date - The date to be changed
  22. * @param duration - The object with years, months, weeks, days, hours, minutes, and seconds to be added.
  23. * @param options - An object with options
  24. *
  25. * @returns The new date with the seconds added
  26. *
  27. * @example
  28. * // Add the following duration to 1 September 2014, 10:19:50
  29. * const result = add(new Date(2014, 8, 1, 10, 19, 50), {
  30. * years: 2,
  31. * months: 9,
  32. * weeks: 1,
  33. * days: 7,
  34. * hours: 5,
  35. * minutes: 9,
  36. * seconds: 30,
  37. * })
  38. * //=> Thu Jun 15 2017 15:29:20
  39. */
  40. function add(date, duration, options) {
  41. const {
  42. years = 0,
  43. months = 0,
  44. weeks = 0,
  45. days = 0,
  46. hours = 0,
  47. minutes = 0,
  48. seconds = 0,
  49. } = duration;
  50. // Add years and months
  51. const _date = (0, _index4.toDate)(date, options?.in);
  52. const dateWithMonths =
  53. months || years
  54. ? (0, _index2.addMonths)(_date, months + years * 12)
  55. : _date;
  56. // Add weeks and days
  57. const dateWithDays =
  58. days || weeks
  59. ? (0, _index.addDays)(dateWithMonths, days + weeks * 7)
  60. : dateWithMonths;
  61. // Add days, hours, minutes, and seconds
  62. const minutesToAdd = minutes + hours * 60;
  63. const secondsToAdd = seconds + minutesToAdd * 60;
  64. const msToAdd = secondsToAdd * 1000;
  65. return (0, _index3.constructFrom)(
  66. options?.in || date,
  67. +dateWithDays + msToAdd,
  68. );
  69. }