calculationDate.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. // CalculationDate 计算两个日期之间相差n年m月y天
  2. export const CalculationDate = (s, e) => {
  3. let startDate = new Date(s);
  4. let endDate = new Date(e);
  5. let numYear = endDate.getFullYear() - startDate.getFullYear();
  6. let numMonth = endDate.getMonth() + 1 - (startDate.getMonth() + 1);
  7. let numDay = 0;
  8. //获取截止月的总天数
  9. let endDateDays = getMonthDay(endDate.getFullYear(), endDate.getMonth() + 1);
  10. //获取截止月的前一个月
  11. let endDatePrevMonthDate = getPreMonth(e);
  12. //获取截止日期的上一个月的总天数
  13. let endDatePrevMonthDays = getMonthDay(endDatePrevMonthDate.getFullYear(), endDatePrevMonthDate.getMonth() + 1);
  14. //获取开始日期的的月份总天数
  15. let startDateMonthDays = getMonthDay(startDate.getFullYear(), startDate.getMonth() + 1);
  16. //判断,截止月是否完全被选中,如果相等,那么代表截止月份全部天数被选择
  17. if (endDate.getDate() == endDateDays) {
  18. numDay = startDateMonthDays - startDate.getDate() + 1;
  19. //如果剩余天数正好与开始日期的天数是一致的,那么月份加1
  20. if (numDay == startDateMonthDays) {
  21. numMonth++;
  22. numDay = 0;
  23. //超过月份了,那么年份加1
  24. if (numMonth == 12) {
  25. numYear++;
  26. numMonth = 0;
  27. }
  28. }
  29. } else {
  30. numDay = endDate.getDate() - startDate.getDate() + 1;
  31. }
  32. //天数小于0,那么向月份借一位
  33. if (numDay < 0) {
  34. //向上一个月借一个月的天数
  35. numDay += endDatePrevMonthDays;
  36. //总月份减去一个月
  37. numMonth = numMonth - 1;
  38. }
  39. //月份小于0,那么向年份借一位
  40. if (numMonth < 0) {
  41. //向上一个年借12个月
  42. numMonth += 12;
  43. //总年份减去一年
  44. numYear = numYear - 1;
  45. }
  46. if (numYear < 0) {
  47. console.log("日期异常");
  48. return;
  49. }
  50. let str = ``;
  51. if (numYear > 0) {
  52. str = str + numYear + "年";
  53. }
  54. if (numMonth > 0) {
  55. str = str + numMonth + "个月";
  56. }
  57. if (numDay > 0) {
  58. str = str + numDay + "天";
  59. }
  60. // console.log(str);
  61. return str
  62. };
  63. // getMonthDay 获取某年某月有多少天
  64. const getMonthDay = (year, month) => {
  65. let days=0
  66. if (month != 2) {
  67. if (month == 4 || month == 6 || month == 9 || month == 11) {
  68. days = 30;
  69. } else {
  70. days = 31;
  71. }
  72. } else {
  73. if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
  74. days = 29;
  75. } else {
  76. days = 28;
  77. }
  78. }
  79. return days;
  80. };
  81. const getPreMonth=(e)=>{
  82. let time = new Date(e)
  83. let year=time.getFullYear()
  84. let month=time.getMonth()
  85. let day=time.getDate()
  86. if(month===0){
  87. year--
  88. }
  89. return new Date(`${year}-${month}-${day}`)
  90. }