getDateDiff.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. var setupDefaults = require('./setupDefaults')
  2. var helperGetDateTime = require('./helperGetDateTime')
  3. var helperNewDate = require('./helperNewDate')
  4. var toStringDate = require('./toStringDate')
  5. var isValidDate = require('./isValidDate')
  6. /**
  7. * 返回两个日期之间差距,如果结束日期小于开始日期done为fasle
  8. *
  9. * @param {Date} startDate 开始日期
  10. * @param {Date} endDate 结束日期或当期日期
  11. * @param {Date} rule 自定义计算规则
  12. * @return {Object}
  13. */
  14. function getDateDiff (startDate, endDate, rules) {
  15. var startTime, endTime, item, diffTime, rule, len, index
  16. var result = { done: false, time: 0 }
  17. startDate = toStringDate(startDate)
  18. endDate = endDate ? toStringDate(endDate) : helperNewDate()
  19. if (isValidDate(startDate) && isValidDate(endDate)) {
  20. startTime = helperGetDateTime(startDate)
  21. endTime = helperGetDateTime(endDate)
  22. if (startTime < endTime) {
  23. diffTime = result.time = endTime - startTime
  24. rule = rules && rules.length > 0 ? rules : setupDefaults.dateDiffRules
  25. result.done = true
  26. for (index = 0, len = rule.length; index < len; index++) {
  27. item = rule[index]
  28. if (diffTime >= item[1]) {
  29. if (index === len - 1) {
  30. result[item[0]] = diffTime || 0
  31. } else {
  32. result[item[0]] = Math.floor(diffTime / item[1])
  33. diffTime -= result[item[0]] * item[1]
  34. }
  35. } else {
  36. result[item[0]] = 0
  37. }
  38. }
  39. }
  40. }
  41. return result
  42. }
  43. module.exports = getDateDiff