index.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. var parse = require('../parse/index.js')
  2. /**
  3. * @category Common Helpers
  4. * @summary Compare the two dates and return -1, 0 or 1.
  5. *
  6. * @description
  7. * Compare the two dates and return 1 if the first date is after the second,
  8. * -1 if the first date is before the second or 0 if dates are equal.
  9. *
  10. * @param {Date|String|Number} dateLeft - the first date to compare
  11. * @param {Date|String|Number} dateRight - the second date to compare
  12. * @returns {Number} the result of the comparison
  13. *
  14. * @example
  15. * // Compare 11 February 1987 and 10 July 1989:
  16. * var result = compareAsc(
  17. * new Date(1987, 1, 11),
  18. * new Date(1989, 6, 10)
  19. * )
  20. * //=> -1
  21. *
  22. * @example
  23. * // Sort the array of dates:
  24. * var result = [
  25. * new Date(1995, 6, 2),
  26. * new Date(1987, 1, 11),
  27. * new Date(1989, 6, 10)
  28. * ].sort(compareAsc)
  29. * //=> [
  30. * // Wed Feb 11 1987 00:00:00,
  31. * // Mon Jul 10 1989 00:00:00,
  32. * // Sun Jul 02 1995 00:00:00
  33. * // ]
  34. */
  35. function compareAsc (dirtyDateLeft, dirtyDateRight) {
  36. var dateLeft = parse(dirtyDateLeft)
  37. var timeLeft = dateLeft.getTime()
  38. var dateRight = parse(dirtyDateRight)
  39. var timeRight = dateRight.getTime()
  40. if (timeLeft < timeRight) {
  41. return -1
  42. } else if (timeLeft > timeRight) {
  43. return 1
  44. } else {
  45. return 0
  46. }
  47. }
  48. module.exports = compareAsc