index.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. * ### v2.0.0 breaking changes:
  15. *
  16. * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
  17. *
  18. * @param {Date|Number} dateLeft - the later date
  19. * @param {Date|Number} dateRight - the earlier date
  20. * @returns {Number} the number of calendar days
  21. * @throws {TypeError} 2 arguments required
  22. *
  23. * @example
  24. * // How many calendar days are between
  25. * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00?
  26. * const result = differenceInCalendarDays(
  27. * new Date(2012, 6, 2, 0, 0),
  28. * new Date(2011, 6, 2, 23, 0)
  29. * )
  30. * //=> 366
  31. * // How many calendar days are between
  32. * // 2 July 2011 23:59:00 and 3 July 2011 00:01:00?
  33. * const result = differenceInCalendarDays(
  34. * new Date(2011, 6, 3, 0, 1),
  35. * new Date(2011, 6, 2, 23, 59)
  36. * )
  37. * //=> 1
  38. */
  39. export default function differenceInCalendarDays(dirtyDateLeft, dirtyDateRight) {
  40. requiredArgs(2, arguments);
  41. var startOfDayLeft = startOfDay(dirtyDateLeft);
  42. var startOfDayRight = startOfDay(dirtyDateRight);
  43. var timestampLeft = startOfDayLeft.getTime() - getTimezoneOffsetInMilliseconds(startOfDayLeft);
  44. var timestampRight = startOfDayRight.getTime() - getTimezoneOffsetInMilliseconds(startOfDayRight); // Round the number of days to the nearest integer
  45. // because the number of milliseconds in a day is not constant
  46. // (e.g. it's different in the day of the daylight saving time clock shift)
  47. return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_DAY);
  48. }