js日期多少小時前、多少分鐘前、多少秒前

恰好項目須要這樣一個功能,順便共享出來給你們玩耍。git

https://github.com/jaywcjlove/date.jsgithub

例子:

dateDiff(Timestamp,now Timestamp)
Timestamp:毫秒code

dateDiff(1411430400000,1421313395359)
//=>"3個月前"

dateDiff(new Date('1987-04-03').getTime())
//=>"28年前"

源碼:

;(function(window){
    /**
     * [dateDiff 算時間差]
     * @param  {[type=Number]} hisTime [歷史時間戳,必傳]
     * @param  {[type=Number]} nowTime [當前時間戳,不傳將獲取當前時間戳]
     * @return {[string]}         [string]
     */
    var dateDiff = function(hisTime,nowTime){
        var now =nowTime?nowTime:new Date().getTime(),
            diffValue = now - hisTime,
            result='',
            minute = 1000 * 60,
            hour = minute * 60,
            day = hour * 24,
            halfamonth = day * 15,
            month = day * 30,
            year = month * 12,
            
            _year = diffValue/year,
            _month =diffValue/month,
            _week =diffValue/(7*day),
            _day =diffValue/day,
            _hour =diffValue/hour,
            _min =diffValue/minute;
            
            if(_year>=1) result=parseInt(_year) + "年前";
            else if(_month>=1) result=parseInt(_month) + "個月前";
            else if(_week>=1) result=parseInt(_week) + "周前";
            else if(_day>=1) result=parseInt(_day) +"天前";
            else if(_hour>=1) result=parseInt(_hour) +"個小時前";
            else if(_min>=1) result=parseInt(_min) +"分鐘前";
            else result="剛剛";
            return result;
    }
    window.dateDiff = dateDiff
})(window);

改爲了型參數,應該是這樣吧get

;(function(window){
    /**
     * [dateDiff 算時間差]
     * @param  {[type=Number]} hisTime [歷史時間戳,必傳]
     * @param  {[type=Number]} nowTime [當前時間戳,不傳將獲取當前時間戳]
     * @return {[string]}         [string]
     */
    var dateDiff = function(hisTime,nowTime){
        if(!arguments.length) return '';
        var arg = arguments,
            now =arg[1]?arg[1]:new Date().getTime(),
            diffValue = now - arg[0],
            result='',

            minute = 1000 * 60,
            hour = minute * 60,
            day = hour * 24,
            halfamonth = day * 15,
            month = day * 30,
            year = month * 12,

            _year = diffValue/year,
            _month =diffValue/month,
            _week =diffValue/(7*day),
            _day =diffValue/day,
            _hour =diffValue/hour,
            _min =diffValue/minute;

            if(_year>=1) result=parseInt(_year) + "年前";
            else if(_month>=1) result=parseInt(_month) + "個月前";
            else if(_week>=1) result=parseInt(_week) + "周前";
            else if(_day>=1) result=parseInt(_day) +"天前";
            else if(_hour>=1) result=parseInt(_hour) +"個小時前";
            else if(_min>=1) result=parseInt(_min) +"分鐘前";
            else result="剛剛";
            return result;
    }
    window.dateDiff = dateDiff
})(window);
相關文章
相關標籤/搜索