插件——時間返回類似 'xx天前xx小時前'

/**
* @Date: 2019-08-14 11:44:46
* @param  指定一個時間戳 setTime 
* @author lg
* @desc: 返回類似幾天前幾小時前
**/
var Time = {
    // 獲取當前時間戳
    getUnix: function () {
        var date = new Date();
        return date.getTime();
    },
    // 獲取今天0點0分0秒的時間戳
    getTodayUnix: function () {
        var date = new Date();
        date.setHours(0);
        date.setMinutes(0);
        date.setSeconds(0);
        date.setMilliseconds(0);
        return date.getTime();
    },
    // 獲取今年1月1日0點0分0秒的時間戳
    getYearUnix: function () {
        var date = new Date();
        date.setMonth(0);
        date.setDate(1);
        date.setHours(0);
        date.setMinutes(0);
        date.setSeconds(0);
        date.setMilliseconds(0);
        return date.getTime();
    },
    // 獲取標準年月日
    getLastDate: function(time) {
        var date = new Date(time);
        var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
        var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
        return date.getFullYear() + '-' + month + "-" + day;
    },
    // 轉換時間
    getFormatTime: function(timestamp) {
        var now = this.getUnix();    //當前時間戳
        var today = this.getTodayUnix(); //今天0點時間戳
        var year = this.getYearUnix();   //今年0點時間戳
        var timer = (now - timestamp) / 1000;   // 轉換爲秒級時間戳
        var tip = '';

        if (timer <= 0) {
            tip = '剛剛';
        } else if (Math.floor(timer/60) <= 0) {
            tip = '剛剛';
        } else if (timer < 3600) {
            tip = Math.floor(timer/60) + '分鐘前';
        } else if (timer >= 3600 && (timestamp - today >= 0) ) {
            tip = Math.floor(timer/3600) + '小時前';
        } else if (timer/86400 <= 31) {
            tip = Math.ceil(timer/86400) + '天前';
        } else {
            tip = this.getLastDate(timestamp);
        }
        return tip;
    }
};
var setTime = new Date('2019-08-10').valueOf()
var callBack = Time.getFormatTime(setTime );
console.log(callBack );//幾天前
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章