addDays.js 1.3 KB

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