eachDayOfInterval.js 1.8 KB

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