時間戳顯示為多少分鍾前,多少天前的JS處理,JS時間格式化,時間戳的轉換


    var dateDiff = function (timestamp) {
        // 補全為13位
        var arrTimestamp = (timestamp + '').split('');
        for (var start = 0; start < 13; start++) {
            if (!arrTimestamp[start]) {
                arrTimestamp[start] = '0';
            }
        }
        timestamp = arrTimestamp.join('') * 1;
        var minute = 1000 * 60;
        var hour = minute * 60;
        var day = hour * 24;
        var halfamonth = day * 15;
        var month = day * 30;
        var now = new Date().getTime();
        var diffValue = now - timestamp;

        // 如果本地時間反而小於變量時間
        if (diffValue < 0) {
            return '不久前';
        }
        // 計算差異時間的量級
        var monthC = diffValue / month;
        var weekC = diffValue / (7 * day);
        var dayC = diffValue / day;
        var hourC = diffValue / hour;
        var minC = diffValue / minute;

        // 數值補0方法
        var zero = function (value) {
            if (value < 10) {
                return '0' + value;
            }
            return value;
        };

        // 使用
        if (monthC > 4) {
            // 超過1年,直接顯示年月日
            return (function () {
                var date = new Date(timestamp);
                return date.getFullYear() + '年' + zero(date.getMonth() + 1) + '月' + zero(date.getDate()) + '日';
            })();
        } else if (monthC >= 1) {
            return parseInt(monthC) + "月前";
        } else if (weekC >= 1) {
            return parseInt(weekC) + "周前";
        } else if (dayC >= 1) {
            return parseInt(dayC) + "天前";
        } else if (hourC >= 1) {
            return parseInt(hourC) + "小時前";
        } else if (minC >= 1) {
            return parseInt(minC) + "分鍾前";
        }
        return '剛剛';
    };
    console.log(dateDiff(1560387311));  // 2014年09月19日
    console.log(dateDiff(1560400790));  // 9月前
    console.log(dateDiff(1550062750));  // 2月前
    console.log(dateDiff(1547384350));  // 3周前
    console.log(dateDiff(1505283100802));  // 1分鍾前

JS時間格式化,時間戳的轉換

//時間轉時間戳
//將Thu Sep 20 2018 16:47:52 GMT+0800 (中國標准時間)轉換為1537433272051

console.log(Date.parse(new Date()))
console.log(new Date().getTime())


//將"2018-09-20 16:50:48"轉換為1537433448000 var timeDate = "2018-09-20 16:50:48"; var Time = new Date(timeDate); var timestemp = Time.getTime(); console.log(timestemp)
  • Date.parse() :時間字符串可以直接Date.parse(datestring),不需要 new Date()
  • Date.getTime() :需要將時間字符串先new Date(),再使用Date.getTime()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM