index.js 1.0 KB

1234567891011121314151617181920212223242526272829303132
  1. import requiredArgs from "../_lib/requiredArgs/index.js";
  2. import getDay from "../getDay/index.js";
  3. import subDays from "../subDays/index.js";
  4. /**
  5. * @name previousDay
  6. * @category Weekday Helpers
  7. * @summary When is the previous day of the week?
  8. *
  9. * @description
  10. * When is the previous day of the week? 0-6 the day of the week, 0 represents Sunday.
  11. *
  12. * @param {Date | number} date - the date to check
  13. * @param {number} day - day of the week
  14. * @returns {Date} - the date is the previous day of week
  15. * @throws {TypeError} - 2 arguments required
  16. *
  17. * @example
  18. * // When is the previous Monday before Mar, 20, 2020?
  19. * const result = previousDay(new Date(2020, 2, 20), 1)
  20. * //=> Mon Mar 16 2020 00:00:00
  21. *
  22. * @example
  23. * // When is the previous Tuesday before Mar, 21, 2020?
  24. * const result = previousDay(new Date(2020, 2, 21), 2)
  25. * //=> Tue Mar 17 2020 00:00:00
  26. */
  27. export default function previousDay(date, day) {
  28. requiredArgs(2, arguments);
  29. var delta = getDay(date) - day;
  30. if (delta <= 0) delta += 7;
  31. return subDays(date, delta);
  32. }