index.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import getTimezoneOffsetInMilliseconds from "../_lib/getTimezoneOffsetInMilliseconds/index.js";
  2. import startOfDay from "../startOfDay/index.js";
  3. import requiredArgs from "../_lib/requiredArgs/index.js";
  4. var MILLISECONDS_IN_DAY = 86400000;
  5. /**
  6. * @name differenceInCalendarDays
  7. * @category Day Helpers
  8. * @summary Get the number of calendar days between the given dates.
  9. *
  10. * @description
  11. * Get the number of calendar days between the given dates. This means that the times are removed
  12. * from the dates and then the difference in days is calculated.
  13. *
  14. * @param {Date|Number} dateLeft - the later date
  15. * @param {Date|Number} dateRight - the earlier date
  16. * @returns {Number} the number of calendar days
  17. * @throws {TypeError} 2 arguments required
  18. *
  19. * @example
  20. * // How many calendar days are between
  21. * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00?
  22. * const result = differenceInCalendarDays(
  23. * new Date(2012, 6, 2, 0, 0),
  24. * new Date(2011, 6, 2, 23, 0)
  25. * )
  26. * //=> 366
  27. * // How many calendar days are between
  28. * // 2 July 2011 23:59:00 and 3 July 2011 00:01:00?
  29. * const result = differenceInCalendarDays(
  30. * new Date(2011, 6, 3, 0, 1),
  31. * new Date(2011, 6, 2, 23, 59)
  32. * )
  33. * //=> 1
  34. */
  35. export default function differenceInCalendarDays(dirtyDateLeft, dirtyDateRight) {
  36. requiredArgs(2, arguments);
  37. var startOfDayLeft = startOfDay(dirtyDateLeft);
  38. var startOfDayRight = startOfDay(dirtyDateRight);
  39. var timestampLeft = startOfDayLeft.getTime() - getTimezoneOffsetInMilliseconds(startOfDayLeft);
  40. var timestampRight = startOfDayRight.getTime() - getTimezoneOffsetInMilliseconds(startOfDayRight);
  41. // Round the number of days to the nearest integer
  42. // because the number of milliseconds in a day is not constant
  43. // (e.g. it's different in the day of the daylight saving time clock shift)
  44. return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_DAY);
  45. }