index.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. var startOfDay = require('../start_of_day/index.js')
  2. var MILLISECONDS_IN_MINUTE = 60000
  3. var MILLISECONDS_IN_DAY = 86400000
  4. /**
  5. * @category Day Helpers
  6. * @summary Get the number of calendar days between the given dates.
  7. *
  8. * @description
  9. * Get the number of calendar 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 calendar days
  14. *
  15. * @example
  16. * // How many calendar days are between
  17. * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00?
  18. * var result = differenceInCalendarDays(
  19. * new Date(2012, 6, 2, 0, 0),
  20. * new Date(2011, 6, 2, 23, 0)
  21. * )
  22. * //=> 366
  23. */
  24. function differenceInCalendarDays (dirtyDateLeft, dirtyDateRight) {
  25. var startOfDayLeft = startOfDay(dirtyDateLeft)
  26. var startOfDayRight = startOfDay(dirtyDateRight)
  27. var timestampLeft = startOfDayLeft.getTime() -
  28. startOfDayLeft.getTimezoneOffset() * MILLISECONDS_IN_MINUTE
  29. var timestampRight = startOfDayRight.getTime() -
  30. startOfDayRight.getTimezoneOffset() * MILLISECONDS_IN_MINUTE
  31. // Round the number of days to the nearest integer
  32. // because the number of milliseconds in a day is not constant
  33. // (e.g. it's different in the day of the daylight saving time clock shift)
  34. return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_DAY)
  35. }
  36. module.exports = differenceInCalendarDays