day.js实现倒计时【23days 02:38:21.198】

倒计时

主要Api

时间差 diff

  • return Number

获取两个 Dayjs 对象的时间差,默认毫秒。

const date1 = dayjs('2019-01-25')
const date2 = dayjs('2018-06-05')
date1.diff(date2) // 20214000000
date1.diff(date2, 'month') // 7
date1.diff(date2, 'month', true) // 7.645161290322581
date1.diff(date2, 'day') // 233

代码

window.requestAnimationFrame = (function(){
    return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        function( callback ){
            window.setTimeout(callback, 1000 / 60);
        };
})();
var timeEle = document.getElementById('time');
var endDate = dayjs('2020-01-04 00:00:00');

function animation(){
    var _ms = endDate.diff(dayjs());
    if(_ms>0){
        var _dd = endDate.diff(dayjs(),'day');
        var _hh = endDate.diff(dayjs(),'hour');
        var _mm = endDate.diff(dayjs(),'minute');
        var _ss = endDate.diff(dayjs(),'second');
        
        // 转换
        var hh = _hh - (_dd*24);
        var mm = _mm - (_hh*60);
        var ss = _ss - (_mm*60);
        var ms = _ms - (_ss*1000);

        // 格式化
        var DD =  ('00'+_dd).slice(-2);
        var HH =  ('00'+hh).slice(-2);
        var MM =  ('00'+mm).slice(-2);
        var SS =  ('00'+ss).slice(-2);
        var MS =  ('000'+ms).slice(-3);
        timeEle.innerHTML = '<span class="time2">'+DD+'</span>days <span class="time2">'+HH+'</span>:<span class="time2">'+MM+'</span>:<span class="time2">'+SS+'</span>.<span class="time3">'+MS+'</span>';
        requestAnimationFrame(animation);
    }else{
        timeEle.innerHTML = 'LOVE';
    }
}
animation();

零时写的倒计时,哈哈哈

推荐阅读更多精彩内容