previousDay.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import { getDay } from "./getDay.js";
  2. import { subDays } from "./subDays.js";
  3. /**
  4. * The {@link previousDay} function options.
  5. */
  6. /**
  7. * @name previousDay
  8. * @category Weekday Helpers
  9. * @summary When is the previous day of the week?
  10. *
  11. * @description
  12. * When is the previous day of the week? 0-6 the day of the week, 0 represents Sunday.
  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 check
  18. * @param day - The day of the week
  19. * @param options - An object with options
  20. *
  21. * @returns The date is the previous day of week
  22. *
  23. * @example
  24. * // When is the previous Monday before Mar, 20, 2020?
  25. * const result = previousDay(new Date(2020, 2, 20), 1)
  26. * //=> Mon Mar 16 2020 00:00:00
  27. *
  28. * @example
  29. * // When is the previous Tuesday before Mar, 21, 2020?
  30. * const result = previousDay(new Date(2020, 2, 21), 2)
  31. * //=> Tue Mar 17 2020 00:00:00
  32. */
  33. export function previousDay(date, day, options) {
  34. let delta = getDay(date, options) - day;
  35. if (delta <= 0) delta += 7;
  36. return subDays(date, delta, options);
  37. }
  38. // Fallback for modularized imports:
  39. export default previousDay;