eachMonthOfInterval.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. "use strict";
  2. exports.eachMonthOfInterval = eachMonthOfInterval;
  3. var _index = require("./toDate.js");
  4. /**
  5. * The {@link eachMonthOfInterval} function options.
  6. */
  7. /**
  8. * @name eachMonthOfInterval
  9. * @category Interval Helpers
  10. * @summary Return the array of months within the specified time interval.
  11. *
  12. * @description
  13. * Return the array of months 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. *
  19. * @returns The array with starts of months from the month of the interval start to the month of the interval end
  20. *
  21. * @example
  22. * // Each month between 6 February 2014 and 10 August 2014:
  23. * const result = eachMonthOfInterval({
  24. * start: new Date(2014, 1, 6),
  25. * end: new Date(2014, 7, 10)
  26. * })
  27. * //=> [
  28. * // Sat Feb 01 2014 00:00:00,
  29. * // Sat Mar 01 2014 00:00:00,
  30. * // Tue Apr 01 2014 00:00:00,
  31. * // Thu May 01 2014 00:00:00,
  32. * // Sun Jun 01 2014 00:00:00,
  33. * // Tue Jul 01 2014 00:00:00,
  34. * // Fri Aug 01 2014 00:00:00
  35. * // ]
  36. */
  37. function eachMonthOfInterval(interval, options) {
  38. const startDate = (0, _index.toDate)(interval.start);
  39. const endDate = (0, _index.toDate)(interval.end);
  40. let reversed = +startDate > +endDate;
  41. const endTime = reversed ? +startDate : +endDate;
  42. const currentDate = reversed ? endDate : startDate;
  43. currentDate.setHours(0, 0, 0, 0);
  44. currentDate.setDate(1);
  45. let step = options?.step ?? 1;
  46. if (!step) return [];
  47. if (step < 0) {
  48. step = -step;
  49. reversed = !reversed;
  50. }
  51. const dates = [];
  52. while (+currentDate <= endTime) {
  53. dates.push((0, _index.toDate)(currentDate));
  54. currentDate.setMonth(currentDate.getMonth() + step);
  55. }
  56. return reversed ? dates.reverse() : dates;
  57. }