index.js 2.2 KB

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