isWithinInterval.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. "use strict";
  2. exports.isWithinInterval = isWithinInterval;
  3. var _index = require("./toDate.js");
  4. /**
  5. * @name isWithinInterval
  6. * @category Interval Helpers
  7. * @summary Is the given date within the interval?
  8. *
  9. * @description
  10. * Is the given date within the interval? (Including start and end.)
  11. *
  12. * @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).
  13. *
  14. * @param date - The date to check
  15. * @param interval - The interval to check
  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 interval start:
  37. * isWithinInterval(date, { start, end: date })
  38. * // => true
  39. *
  40. * @example
  41. * // For date equal to interval end:
  42. * isWithinInterval(date, { start: date, end })
  43. * // => true
  44. */
  45. function isWithinInterval(date, interval) {
  46. const time = +(0, _index.toDate)(date);
  47. const [startTime, endTime] = [
  48. +(0, _index.toDate)(interval.start),
  49. +(0, _index.toDate)(interval.end),
  50. ].sort((a, b) => a - b);
  51. return time >= startTime && time <= endTime;
  52. }