js计算两个日期差

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中测试结果如下:
 

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值