index.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. var parse = require('../parse/index.js')
  2. var differenceInCalendarDays = require('../difference_in_calendar_days/index.js')
  3. var compareAsc = require('../compare_asc/index.js')
  4. /**
  5. * @category Day Helpers
  6. * @summary Get the number of full days between the given dates.
  7. *
  8. * @description
  9. * Get the number of full days between the given dates.
  10. *
  11. * @param {Date|String|Number} dateLeft - the later date
  12. * @param {Date|String|Number} dateRight - the earlier date
  13. * @returns {Number} the number of full days
  14. *
  15. * @example
  16. * // How many full days are between
  17. * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00?
  18. * var result = differenceInDays(
  19. * new Date(2012, 6, 2, 0, 0),
  20. * new Date(2011, 6, 2, 23, 0)
  21. * )
  22. * //=> 365
  23. */
  24. function differenceInDays (dirtyDateLeft, dirtyDateRight) {
  25. var dateLeft = parse(dirtyDateLeft)
  26. var dateRight = parse(dirtyDateRight)
  27. var sign = compareAsc(dateLeft, dateRight)
  28. var difference = Math.abs(differenceInCalendarDays(dateLeft, dateRight))
  29. dateLeft.setDate(dateLeft.getDate() - sign * difference)
  30. // Math.abs(diff in full days - diff in calendar days) === 1 if last calendar day is not full
  31. // If so, result must be decreased by 1 in absolute value
  32. var isLastDayNotFull = compareAsc(dateLeft, dateRight) === -sign
  33. return sign * (difference - isLastDayNotFull)
  34. }
  35. module.exports = differenceInDays