Source: compareAsc/index.js

  1. import toDate from '../toDate/index'
  2. import requiredArgs from '../_lib/requiredArgs/index'
  3. /**
  4. * @name compareAsc
  5. * @category Common Helpers
  6. * @summary Compare the two dates and return -1, 0 or 1.
  7. *
  8. * @description
  9. * Compare the two dates and return 1 if the first date is after the second,
  10. * -1 if the first date is before the second or 0 if dates are equal.
  11. *
  12. * ### v2.0.0 breaking changes:
  13. *
  14. * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
  15. *
  16. * @param {Date|Number} dateLeft - the first date to compare
  17. * @param {Date|Number} dateRight - the second date to compare
  18. * @returns {Number} the result of the comparison
  19. * @throws {TypeError} 2 arguments required
  20. *
  21. * @example
  22. * // Compare 11 February 1987 and 10 July 1989:
  23. * var result = compareAsc(new Date(1987, 1, 11), new Date(1989, 6, 10))
  24. * //=> -1
  25. *
  26. * @example
  27. * // Sort the array of dates:
  28. * var result = [
  29. * new Date(1995, 6, 2),
  30. * new Date(1987, 1, 11),
  31. * new Date(1989, 6, 10)
  32. * ].sort(compareAsc)
  33. * //=> [
  34. * // Wed Feb 11 1987 00:00:00,
  35. * // Mon Jul 10 1989 00:00:00,
  36. * // Sun Jul 02 1995 00:00:00
  37. * // ]
  38. */
  39. export default function compareAsc(dirtyDateLeft, dirtyDateRight) {
  40. requiredArgs(2, arguments)
  41. var dateLeft = toDate(dirtyDateLeft)
  42. var dateRight = toDate(dirtyDateRight)
  43. var diff = dateLeft.getTime() - dateRight.getTime()
  44. if (diff < 0) {
  45. return -1
  46. } else if (diff > 0) {
  47. return 1
  48. // Return 0 if diff is 0; return NaN if diff is NaN
  49. } else {
  50. return diff
  51. }
  52. }