calAgeToMonth.js 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. export default function setCompareRegistrationTimeText(startDate, endDate) {
  2. // if (!val) {
  3. // this.ruleForm.compareRegistrationTimeText = '--'
  4. // return
  5. // }
  6. const date = new Date(startDate) // 转换时间格式
  7. const year = date.getFullYear() // 取当年的年
  8. const month = date.getMonth() + 1 // 取当年的月(月份加一)
  9. const dd = date.getDate() // 取当年的日期
  10. const nowDate = new Date(endDate) // 取现在的时间
  11. const nowYear = nowDate.getFullYear() // 取现在的年
  12. const nowMonth = nowDate.getMonth() + 1 // 取现在的月(月份加一)
  13. const nowDd = nowDate.getDate() // 取现在的日期
  14. /**
  15. * 日期计算(结束 - 开始)
  16. * 1-1当差值为正,就相差多少天
  17. * 1-1-1例如: (2021/3/15 - 2022/4/18) ===== 18-15 > 0 日期相差3天
  18. * 1-2当差值为负,计算从开始时间的日期到结束时间的日期相差几天
  19. * 1-2-1例如:(2021/3/15 - 2022/4/10) ===== 10-15 < 0
  20. * 其实就是计算从3/15 到 4、10号中间过了多少天
  21. * 1-2-1-1:方法: 其实就是计算3/15 到 3/31 号过了多少天,再加上 4月过的10天
  22. */
  23. const restDd =
  24. nowDd - dd < 0 ? lastDay(nowMonth - 1, year) - dd + nowDd : nowDd - dd
  25. /**
  26. * 月份计算(结束 - 开始)
  27. * 1-1当差值为正,就相差多少月
  28. * 1-1-1例如: (2021/3/15 - 2022/4/18) ===== 4-3 > 0 月份相差1月
  29. * 1-2当差值为负,计算从开始时间的月份到结束时间的月份相差几天
  30. * 1-2-1例如:(2021/5/15 - 2022/4/10) ===== 4-5 < 0
  31. * 其实就是计算从5月到第二年4月过了多少月
  32. * 1-2-1-1:方法: 向年借一年为12月计算过了多少月
  33. */
  34. const restMonth =
  35. nowMonth - month < 0 ? 12 + nowMonth - month : nowMonth - month
  36. /**
  37. * 年份计算(结束 - 开始)
  38. * 直接限制结束比开始大,只有0/正数
  39. */
  40. const restYear = nowYear - year
  41. /**
  42. * 计算借位的问题
  43. */
  44. let resultMonth = restMonth
  45. let resultYear = restYear
  46. // 日期小说明借了月
  47. if (nowDd < dd) {
  48. resultMonth = restMonth - 1 < 0 ? restMonth - 1 + 12 : restMonth - 1
  49. }
  50. // 月份小借了年 或者 日期小,月份刚好一致,因为日期借了月份,导致月份减1,所以减年
  51. if (nowMonth < month || (nowDd < dd && nowMonth === month)) {
  52. resultYear = restYear - 1
  53. }
  54. let str = {
  55. year: resultYear,
  56. month: resultMonth,
  57. day: restDd
  58. }
  59. return str
  60. }
  61. /**
  62. * 判断每年的每个月的最后一天是几号
  63. * @param mo-月份
  64. * @param year-年份
  65. * @returns {number}
  66. */
  67. const lastDay = (mo, year) => {
  68. if (mo === 4 || mo === 6 || mo === 9 || mo === 11) {
  69. return 30
  70. }
  71. //2月
  72. else if (mo === 2) {
  73. if (isLeapYear(year)) {
  74. return 29
  75. } else {
  76. return 28
  77. }
  78. }
  79. //大月
  80. else {
  81. return 31
  82. }
  83. }
  84. /**
  85. * 判断是否是闰年
  86. * @param Year-年份
  87. * @returns {boolean}
  88. */
  89. const isLeapYear = (Year) => {
  90. return (Year % 4 === 0 && Year % 100 !== 0) || Year % 400 === 0
  91. }