isWithinInterval.js 1.4 KB

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