eachMonthOfInterval.mjs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { toDate } from "./toDate.mjs";
  2. /**
  3. * The {@link eachMonthOfInterval} function options.
  4. */
  5. /**
  6. * @name eachMonthOfInterval
  7. * @category Interval Helpers
  8. * @summary Return the array of months within the specified time interval.
  9. *
  10. * @description
  11. * Return the array of months 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. *
  17. * @returns The array with starts of months from the month of the interval start to the month of the interval end
  18. *
  19. * @example
  20. * // Each month between 6 February 2014 and 10 August 2014:
  21. * const result = eachMonthOfInterval({
  22. * start: new Date(2014, 1, 6),
  23. * end: new Date(2014, 7, 10)
  24. * })
  25. * //=> [
  26. * // Sat Feb 01 2014 00:00:00,
  27. * // Sat Mar 01 2014 00:00:00,
  28. * // Tue Apr 01 2014 00:00:00,
  29. * // Thu May 01 2014 00:00:00,
  30. * // Sun Jun 01 2014 00:00:00,
  31. * // Tue Jul 01 2014 00:00:00,
  32. * // Fri Aug 01 2014 00:00:00
  33. * // ]
  34. */
  35. export function eachMonthOfInterval(interval, options) {
  36. const startDate = toDate(interval.start);
  37. const endDate = toDate(interval.end);
  38. let reversed = +startDate > +endDate;
  39. const endTime = reversed ? +startDate : +endDate;
  40. const currentDate = reversed ? endDate : startDate;
  41. currentDate.setHours(0, 0, 0, 0);
  42. currentDate.setDate(1);
  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(toDate(currentDate));
  52. currentDate.setMonth(currentDate.getMonth() + step);
  53. }
  54. return reversed ? dates.reverse() : dates;
  55. }
  56. // Fallback for modularized imports:
  57. export default eachMonthOfInterval;