isWithinInterval.mjs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { toDate } from "./toDate.mjs";
  2. /**
  3. * @name isWithinInterval
  4. * @category Interval Helpers
  5. * @summary Is the given date within the interval?
  6. *
  7. * @description
  8. * Is the given date within the interval? (Including start and end.)
  9. *
  10. * @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).
  11. *
  12. * @param date - The date to check
  13. * @param interval - The interval to check
  14. *
  15. * @returns The date is within the interval
  16. *
  17. * @example
  18. * // For the date within the interval:
  19. * isWithinInterval(new Date(2014, 0, 3), {
  20. * start: new Date(2014, 0, 1),
  21. * end: new Date(2014, 0, 7)
  22. * })
  23. * //=> true
  24. *
  25. * @example
  26. * // For the date outside of the interval:
  27. * isWithinInterval(new Date(2014, 0, 10), {
  28. * start: new Date(2014, 0, 1),
  29. * end: new Date(2014, 0, 7)
  30. * })
  31. * //=> false
  32. *
  33. * @example
  34. * // For date equal to interval start:
  35. * isWithinInterval(date, { start, end: date })
  36. * // => true
  37. *
  38. * @example
  39. * // For date equal to interval end:
  40. * isWithinInterval(date, { start: date, end })
  41. * // => true
  42. */
  43. export function isWithinInterval(date, interval) {
  44. const time = +toDate(date);
  45. const [startTime, endTime] = [
  46. +toDate(interval.start),
  47. +toDate(interval.end),
  48. ].sort((a, b) => a - b);
  49. return time >= startTime && time <= endTime;
  50. }
  51. // Fallback for modularized imports:
  52. export default isWithinInterval;