JS差距时间代码

dhso
2017/11/21 14:38
统计中

经常看到一些时间提示是 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;
    };

本文为 dhso 原创

发布在 http://blog.minws.com/jschai-ju-shi-jian-dai-ma/

如有转载,请标明来源!

作者信息
姓名:dhso
热评文章
最新评论
文章概览