index.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. var parse = require('../parse/index.js')
  2. /**
  3. * @category Day Helpers
  4. * @summary Return the array of dates within the specified range.
  5. *
  6. * @description
  7. * Return the array of dates within the specified range.
  8. *
  9. * @param {Date|String|Number} startDate - the first date
  10. * @param {Date|String|Number} endDate - the last date
  11. * @param {Number} [step=1] - the step between each day
  12. * @returns {Date[]} the array with starts of days from the day of startDate to the day of endDate
  13. * @throws {Error} startDate cannot be after endDate
  14. *
  15. * @example
  16. * // Each day between 6 October 2014 and 10 October 2014:
  17. * var result = eachDay(
  18. * new Date(2014, 9, 6),
  19. * new Date(2014, 9, 10)
  20. * )
  21. * //=> [
  22. * // Mon Oct 06 2014 00:00:00,
  23. * // Tue Oct 07 2014 00:00:00,
  24. * // Wed Oct 08 2014 00:00:00,
  25. * // Thu Oct 09 2014 00:00:00,
  26. * // Fri Oct 10 2014 00:00:00
  27. * // ]
  28. */
  29. function eachDay (dirtyStartDate, dirtyEndDate, dirtyStep) {
  30. var startDate = parse(dirtyStartDate)
  31. var endDate = parse(dirtyEndDate)
  32. var step = dirtyStep !== undefined ? dirtyStep : 1
  33. var endTime = endDate.getTime()
  34. if (startDate.getTime() > endTime) {
  35. throw new Error('The first date cannot be after the second date')
  36. }
  37. var dates = []
  38. var currentDate = startDate
  39. currentDate.setHours(0, 0, 0, 0)
  40. while (currentDate.getTime() <= endTime) {
  41. dates.push(parse(currentDate))
  42. currentDate.setDate(currentDate.getDate() + step)
  43. }
  44. return dates
  45. }
  46. module.exports = eachDay