addDays.mjs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import { toDate } from "./toDate.mjs";
  2. import { constructFrom } from "./constructFrom.mjs";
  3. /**
  4. * @name addDays
  5. * @category Day Helpers
  6. * @summary Add the specified number of days to the given date.
  7. *
  8. * @description
  9. * Add the specified number of days to the given date.
  10. *
  11. * @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).
  12. *
  13. * @param date - The date to be changed
  14. * @param amount - The amount of days to be added.
  15. *
  16. * @returns The new date with the days added
  17. *
  18. * @example
  19. * // Add 10 days to 1 September 2014:
  20. * const result = addDays(new Date(2014, 8, 1), 10)
  21. * //=> Thu Sep 11 2014 00:00:00
  22. */
  23. export function addDays(date, amount) {
  24. const _date = toDate(date);
  25. if (isNaN(amount)) return constructFrom(date, NaN);
  26. if (!amount) {
  27. // If 0 days, no-op to avoid changing times in the hour before end of DST
  28. return _date;
  29. }
  30. _date.setDate(_date.getDate() + amount);
  31. return _date;
  32. }
  33. // Fallback for modularized imports:
  34. export default addDays;