previousDay.mjs 1.1 KB

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