index.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import toDate from "../toDate/index.js";
  2. import requiredArgs from "../_lib/requiredArgs/index.js";
  3. /**
  4. * @name eachMonthOfInterval
  5. * @category Interval Helpers
  6. * @summary Return the array of months within the specified time interval.
  7. *
  8. * @description
  9. * Return the array of months within the specified time interval.
  10. *
  11. * @param {Interval} interval - the interval. See [Interval]{@link https://date-fns.org/docs/Interval}
  12. * @returns {Date[]} the array with starts of months from the month of the interval start to the month of the interval end
  13. * @throws {TypeError} 1 argument required
  14. * @throws {RangeError} The start of an interval cannot be after its end
  15. * @throws {RangeError} Date in interval cannot be `Invalid Date`
  16. *
  17. * @example
  18. * // Each month between 6 February 2014 and 10 August 2014:
  19. * var result = eachMonthOfInterval({
  20. * start: new Date(2014, 1, 6),
  21. * end: new Date(2014, 7, 10)
  22. * })
  23. * //=> [
  24. * // Sat Feb 01 2014 00:00:00,
  25. * // Sat Mar 01 2014 00:00:00,
  26. * // Tue Apr 01 2014 00:00:00,
  27. * // Thu May 01 2014 00:00:00,
  28. * // Sun Jun 01 2014 00:00:00,
  29. * // Tue Jul 01 2014 00:00:00,
  30. * // Fri Aug 01 2014 00:00:00
  31. * // ]
  32. */
  33. export default function eachMonthOfInterval(dirtyInterval) {
  34. requiredArgs(1, arguments);
  35. var interval = dirtyInterval || {};
  36. var startDate = toDate(interval.start);
  37. var endDate = toDate(interval.end);
  38. var endTime = endDate.getTime();
  39. var dates = []; // Throw an exception if start date is after end date or if any date is `Invalid Date`
  40. if (!(startDate.getTime() <= endTime)) {
  41. throw new RangeError('Invalid interval');
  42. }
  43. var currentDate = startDate;
  44. currentDate.setHours(0, 0, 0, 0);
  45. currentDate.setDate(1);
  46. while (currentDate.getTime() <= endTime) {
  47. dates.push(toDate(currentDate));
  48. currentDate.setMonth(currentDate.getMonth() + 1);
  49. }
  50. return dates;
  51. }