index.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import toDate from "../toDate/index.js";
  2. import requiredArgs from "../_lib/requiredArgs/index.js";
  3. /**
  4. * @name isWithinInterval
  5. * @category Interval Helpers
  6. * @summary Is the given date within the interval?
  7. *
  8. * @description
  9. * Is the given date within the interval? (Including start and end.)
  10. *
  11. * @param {Date|Number} date - the date to check
  12. * @param {Interval} interval - the interval to check
  13. * @returns {Boolean} the date is within the interval
  14. * @throws {TypeError} 2 arguments required
  15. * @throws {RangeError} The start of an interval cannot be after its end
  16. * @throws {RangeError} Date in interval cannot be `Invalid Date`
  17. *
  18. * @example
  19. * // For the date within the interval:
  20. * isWithinInterval(new Date(2014, 0, 3), {
  21. * start: new Date(2014, 0, 1),
  22. * end: new Date(2014, 0, 7)
  23. * })
  24. * //=> true
  25. *
  26. * @example
  27. * // For the date outside of the interval:
  28. * isWithinInterval(new Date(2014, 0, 10), {
  29. * start: new Date(2014, 0, 1),
  30. * end: new Date(2014, 0, 7)
  31. * })
  32. * //=> false
  33. *
  34. * @example
  35. * // For date equal to interval start:
  36. * isWithinInterval(date, { start, end: date }) // => true
  37. *
  38. * @example
  39. * // For date equal to interval end:
  40. * isWithinInterval(date, { start: date, end }) // => true
  41. */
  42. export default function isWithinInterval(dirtyDate, interval) {
  43. requiredArgs(2, arguments);
  44. var time = toDate(dirtyDate).getTime();
  45. var startTime = toDate(interval.start).getTime();
  46. var endTime = toDate(interval.end).getTime();
  47. // Throw an exception if start date is after end date or if any date is `Invalid Date`
  48. if (!(startTime <= endTime)) {
  49. throw new RangeError('Invalid interval');
  50. }
  51. return time >= startTime && time <= endTime;
  52. }