如果出现不准确的情况请评论反馈!

function betweenDate(date1Arr, date2Arr) {
    let date1 = new Date(date1Arr.join('/'));
    let date2 = new Date(date2Arr.join('/'));
    let allBetweenDays = Math.floor((date1 - date2) / 1000 / 60 / 60 / 24);
    if (allBetweenDays < 1) {
        let _t = date1;
        date1 = date2;
        date2 = _t;
    }
    let result = '';
    let betweenDay = date1.getDate() - date2.getDate();
    let betweenMonth = date1.getMonth() - date2.getMonth();
    let betweenYear = date1.getFullYear() - date2.getFullYear();

    if (betweenDay < 0) {
        let _date = new Date(date1.getFullYear(), date1.getMonth() === 0 ? 12 : date1.getMonth() - 1, 0);
        betweenDay = date1.getDate() + _date.getDate() - date2.getDate();
        betweenMonth = betweenMonth - 1;
    }
    betweenYear = betweenMonth < 0 ? betweenYear - 1 : betweenYear;
    betweenMonth = betweenMonth < 0 ? betweenMonth + 12 : betweenMonth;
    result = (betweenYear > 0 ? betweenYear + '年' : '') + (betweenMonth > 0 ? betweenMonth + '月' : '') + (betweenDay > 0 ? betweenDay + '天' : '');
    return result;
}

console.log(betweenDate([2018, 5, 22], [2020, 7, 20])); // 2年1月29天
console.log(betweenDate([2019, 12, 30], [2020, 3, 1])); // 2月2天
console.log(betweenDate([2019, 2, 3], [2020, 1, 1]));   // 10月29天
console.log(betweenDate([2020, 2, 1], [2020, 2, 2]));   // 1天
console.log(betweenDate([2020, 2, 1], [2020, 3, 1]));   // 1月
console.log(betweenDate([2019, 2, 1], [2020, 2, 1]));   // 1年

标签: Javascript

评论已关闭