123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- // CalculationDate 计算两个日期之间相差n年m月y天
- export const CalculationDate = (s, e) => {
- let startDate = new Date(s);
- let endDate = new Date(e);
- let numYear = endDate.getFullYear() - startDate.getFullYear();
- let numMonth = endDate.getMonth() + 1 - (startDate.getMonth() + 1);
- let numDay = 0;
- //获取截止月的总天数
- let endDateDays = getMonthDay(endDate.getFullYear(), endDate.getMonth() + 1);
- //获取截止月的前一个月
- let endDatePrevMonthDate = getPreMonth(e);
- //获取截止日期的上一个月的总天数
- let endDatePrevMonthDays = getMonthDay(endDatePrevMonthDate.getFullYear(), endDatePrevMonthDate.getMonth() + 1);
- //获取开始日期的的月份总天数
- let startDateMonthDays = getMonthDay(startDate.getFullYear(), startDate.getMonth() + 1);
- //判断,截止月是否完全被选中,如果相等,那么代表截止月份全部天数被选择
- if (endDate.getDate() == endDateDays) {
- numDay = startDateMonthDays - startDate.getDate() + 1;
- //如果剩余天数正好与开始日期的天数是一致的,那么月份加1
- if (numDay == startDateMonthDays) {
- numMonth++;
- numDay = 0;
- //超过月份了,那么年份加1
- if (numMonth == 12) {
- numYear++;
- numMonth = 0;
- }
- }
- } else {
- numDay = endDate.getDate() - startDate.getDate() + 1;
- }
- //天数小于0,那么向月份借一位
- if (numDay < 0) {
- //向上一个月借一个月的天数
- numDay += endDatePrevMonthDays;
- //总月份减去一个月
- numMonth = numMonth - 1;
- }
- //月份小于0,那么向年份借一位
- if (numMonth < 0) {
- //向上一个年借12个月
- numMonth += 12;
- //总年份减去一年
- numYear = numYear - 1;
- }
- if (numYear < 0) {
- console.log("日期异常");
- return;
- }
- let str = ``;
- if (numYear > 0) {
- str = str + numYear + "年";
- }
- if (numMonth > 0) {
- str = str + numMonth + "个月";
- }
- if (numDay > 0) {
- str = str + numDay + "天";
- }
- // console.log(str);
- return str
- };
- // getMonthDay 获取某年某月有多少天
- const getMonthDay = (year, month) => {
- let days=0
- if (month != 2) {
- if (month == 4 || month == 6 || month == 9 || month == 11) {
- days = 30;
- } else {
- days = 31;
- }
- } else {
- if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
- days = 29;
- } else {
- days = 28;
- }
- }
- return days;
- };
- const getPreMonth=(e)=>{
- let time = new Date(e)
- let year=time.getFullYear()
- let month=time.getMonth()
- let day=time.getDate()
- if(month===0){
- year--
- }
- return new Date(`${year}-${month}-${day}`)
- }
|