下面的實現要依賴 moment.js 這個第工具,下載:http://momentjs.cn/docsjavascript
以下,咱們指定一個時間如: endDate = 2016-07-13 18:30:00
startDate= 當前java
如功能作一個從開始時間起,倒計時到結束時間:工具
<div id="continer"></div> var timer = function(){ var endDate = new Date("2016-07-13 18:30:10"); var diffSecond = parseInt((endDate-new Date())/1000); //結束時間到如今差的秒數 if(diffSecond>0){ var offset = moment.duration(diffSecond, 'seconds'); var month = offset.months(); var day = offset.days(); var hour = offset.hours(); var minute = offset.minutes(); var second = offset.seconds(); var diff = moment({ month :month, day :day, hour :hour, minute :minute, second :second}); $("#continer").text(diff.format("HH:mm:ss")); }else{ //timeout.. } } var id = setInterval(timer,1000);
結果:code
01:39:40 orm
下面咱們把結束時間調整致:2016-07-15 18:30:00ip
var timer = function(){ var endDate = new Date("2016-07-15 18:30:10"); var diffSecond = parseInt((endDate-new Date())/1000); //結束時間到如今差的秒數 if(diffSecond>0){ var offset = moment.duration(diffSecond, 'seconds'); var month = offset.months(); var day = offset.days(); var hour = offset.hours(); var minute = offset.minutes(); var second = offset.seconds(); var diff = moment({ month :month, day :day, hour :hour, minute :minute, second :second}); if(day>0){ $("#continer").text(diff.format("DD天 HH:mm:ss")); }else{ $("#continer").text(diff.format("HH:mm:ss")); } }else{ //timeout.. } } var id = setInterval(timer,1000);
結果:get
2天 01:39:40 io