eachDayOfInterval.mjs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { toDate } from "./toDate.mjs";
  2. /**
  3. * The {@link eachDayOfInterval} function options.
  4. */
  5. /**
  6. * @name eachDayOfInterval
  7. * @category Interval Helpers
  8. * @summary Return the array of dates within the specified time interval.
  9. *
  10. * @description
  11. * Return the array of dates within the specified time interval.
  12. *
  13. * @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).
  14. *
  15. * @param interval - The interval.
  16. * @param options - An object with options.
  17. *
  18. * @returns The array with starts of days from the day of the interval start to the day of the interval end
  19. *
  20. * @example
  21. * // Each day between 6 October 2014 and 10 October 2014:
  22. * const result = eachDayOfInterval({
  23. * start: new Date(2014, 9, 6),
  24. * end: new Date(2014, 9, 10)
  25. * })
  26. * //=> [
  27. * // Mon Oct 06 2014 00:00:00,
  28. * // Tue Oct 07 2014 00:00:00,
  29. * // Wed Oct 08 2014 00:00:00,
  30. * // Thu Oct 09 2014 00:00:00,
  31. * // Fri Oct 10 2014 00:00:00
  32. * // ]
  33. */
  34. export function eachDayOfInterval(interval, options) {
  35. const startDate = toDate(interval.start);
  36. const endDate = toDate(interval.end);
  37. let reversed = +startDate > +endDate;
  38. const endTime = reversed ? +startDate : +endDate;
  39. const currentDate = reversed ? endDate : startDate;
  40. currentDate.setHours(0, 0, 0, 0);
  41. let step = options?.step ?? 1;
  42. if (!step) return [];
  43. if (step < 0) {
  44. step = -step;
  45. reversed = !reversed;
  46. }
  47. const dates = [];
  48. while (+currentDate <= endTime) {
  49. dates.push(toDate(currentDate));
  50. currentDate.setDate(currentDate.getDate() + step);
  51. currentDate.setHours(0, 0, 0, 0);
  52. }
  53. return reversed ? dates.reverse() : dates;
  54. }
  55. // Fallback for modularized imports:
  56. export default eachDayOfInterval;