计算两个日期相差多少年月日

2020-01-11  本文已影响0人  张晓畅

上来就干货

/**
 * @description 是否闰年
 * @param {Number} year 年份
 * @return {Boolean} result
 */
const isLeapYear = (year) => {
    return (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0);
}
/**
 * @description 获取某月有几天
 * @param {Number} year 年份
 * @param {Number} month 月份
 * @return {Number} 天数
 */
const getMonthDays = function (year, month) {
    if (!month) {
        year -= 1;
        month = 12;
    }
    let aMonthDays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    if (isLeapYear(year)) {
        aMonthDays[2] = 29;
    }
    return aMonthDays[month];
};
/**
 * @description 计算两个日期相差多少年月日
 * @param {String} startDate 开始日期
 * @param {String} endDate 结束日期 默认当天
 * @return {Object} 相差的年月日
 */
const getDateSpace = (startDate, endDate) => {
    // 没有开始日期
    if (!startDate) return '没有开始日期';

    // ios只支持/
    const start = new Date(startDate.replace(/-/g, "/")),
        end = endDate ? new Date(endDate.replace(/-/g, "/")) : new Date();

    // 两个日期的时间戳
    const startTime = start.getTime(),
        endTime = end.getTime();

    // 开始日期大于结束日期
    if (endTime < startTime) return '开始日期不能大于结束日期';

    // 开始日期的年月日
    const startY = start.getFullYear(),
        startM = start.getMonth() + 1,
        startD = start.getDate();

    // 结束日期的年月日
    const endY = end.getFullYear(),
        endM = end.getMonth() + 1,
        endD = end.getDate();

    // 相差的年数
    let yearSpace = endY - startY;

    // 两个日期之间相差的月数
    let monthSpace = endM - startM;
    // 开始日期的月份大于结束日期的月份,则年数要退1,即12个月
    if (startM > endM) {
        yearSpace -= 1;
        monthSpace += 12;
    }
    // 两个日期月份相等,开始日期大于结束日期
    if (startM == endM && startD > endD) {
        yearSpace -= 1;
        monthSpace += 12;
    }
    // 开始日期大于结束日期,月数要减1
    if (startD > endD) {
        monthSpace -= 1;
    }

    // 结束时期上一个月的天数
    const pmd = getMonthDays(endY, endM - 1);
    // 开始日期不满一个月的天数(如果开始日期大于结束时期上一个月的天数,则算满月)
    const startDays = startD > pmd ? 0 : pmd - startD;

    // 两日期相差天数(开始日期不满一个月的天数和结束日期的天数之和)
    let daySpace = startDays + endD;
    // 相差天数大于等于上一个月天数则应该减去满月的天数
    if (daySpace >= pmd) {
        daySpace -= pmd;
    }
    // 两个日期的日相同则相差天数为0
    if (startD == endD) {
        daySpace = 0;
    }

    console.log(`${startDate}到${endDate || '今天'}相差${yearSpace}年${monthSpace}月${daySpace}天`);

    return { yearSpace, monthSpace, daySpace }
}

export default getDateSpace
上一篇下一篇

猜你喜欢

热点阅读