js计算两个日期差

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/p3118601/article/details/77852997
function timeDifc(start,end){
    let starts = new Date(start),ends = new Date(end),message = '';
    if (starts.getTime() > ends.getTime())
        return message = "现在的时间小于以前的时间!";

    if ((ends.getTime() - starts.getTime())/(1000*60) < 1)
        return message = "刚刚";

    if (ends.getFullYear() > starts.getFullYear() && ends.getMonth() >= starts.getMonth())
        message += ends.getFullYear() - starts.getFullYear() + "年";

    if (ends.getMonth() > starts.getMonth() && ends.getDate() >= starts.getDate())
        message += ends.getMonth() - starts.getMonth() + "个月";

    if (ends.getDate() > starts.getDate() && ends.getHours() >= starts.getHours())
        message += ends.getDate() - starts.getDate() + "天";

    if (ends.getHours() > starts.getHours() && ends.getMinutes() >= starts.getMinutes())
        message += ends.getHours() - starts.getHours() + "小时";

    if (ends.getMinutes() > starts.getMinutes())
        message += ends.getMinutes() - starts.getMinutes() + "分钟";

    return message;
};

//  注:上边的变量是用let声明的(es6语法),下边是用babel编译后的

function timeDifc(start, end) {
    var starts = new Date(start),
        ends = new Date(end),
        message = '';
    if (starts.getTime() > ends.getTime()) return message = "现在的时间小于以前的时间!";

    if ((ends.getTime() - starts.getTime()) / (1000 * 60) < 1) return message = "刚刚";

    if (ends.getFullYear() > starts.getFullYear() && ends.getMonth() >= starts.getMonth()) message += ends.getFullYear() - starts.getFullYear() + "年";

    if (ends.getMonth() > starts.getMonth() && ends.getDate() >= starts.getDate()) message += ends.getMonth() - starts.getMonth() + "个月";

    if (ends.getDate() > starts.getDate() && ends.getHours() >= starts.getHours()) message += ends.getDate() - starts.getDate() + "天";

    if (ends.getHours() > starts.getHours() && ends.getMinutes() >= starts.getMinutes()) message += ends.getHours() - starts.getHours() + "小时";

    if (ends.getMinutes() > starts.getMinutes()) message += ends.getMinutes() - starts.getMinutes() + "分钟";

    return message;
};


在浏览器的console中测试结果如下:


猜你喜欢

转载自blog.csdn.net/p3118601/article/details/77852997