JS差距时间代码

2017-11-21 / 0 评论 / 142 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2021年10月27日,已超过1121天没有更新,若内容或图片失效,请留言反馈。

经常看到一些时间提示是 1小时前,2分钟前,3天前等等的差距时间,这些是怎么实现的呢?看下面的方法!

代码实现

function timeDifference(tmpTime) {
        var mm = 1000;
        var minute = mm * 60;
        var hour = minute * 60;
        var day = hour * 24;
        var month = day * 30;
        var ansTimeDifference = 0;
        var tmpTimeStamp = tmpTime ? Date.parse(tmpTime.replace(/-/gi, "/")) : new Date().getTime();
        var nowTime = new Date().getTime();
        var tmpTimeDifference = nowTime - tmpTimeStamp;
        if (tmpTimeDifference < 0) {
            console.warn("开始日期大于结束日期,计算失败!");
            return 0;
        }
        var DifferebceMonth = tmpTimeDifference / month;
        var DifferebceWeek = tmpTimeDifference / (7 * day);
        var DifferebceDay = tmpTimeDifference / day;
        var DifferebceHour = tmpTimeDifference / hour;
        var DifferebceMinute = tmpTimeDifference / minute;
        if (DifferebceMonth >= 1) {
            return tmpTime;
        } else if (DifferebceWeek >= 1) {
            ansTimeDifference = parseInt(DifferebceWeek) + "个星期前";
        } else if (DifferebceDay >= 1) {
            ansTimeDifference = parseInt(DifferebceDay) + "天前";
        } else if (DifferebceHour >= 1) {
            ansTimeDifference = parseInt(DifferebceHour) + "个小时前";
        } else if (DifferebceMinute >= 1) {
            ansTimeDifference = parseInt(DifferebceMinute) + "分钟前";
        } else {
            ansTimeDifference = "刚刚";
        }
        return ansTimeDifference;
    };

0

评论 (0)

取消