2017-06-20 379 views
-1

我创建了倒计时,但它返回的是负数输出而不是正数。我研究了为什么发生这种情况的原因,但没有运气。有谁知道为什么倒数可以返回负值?并在我的代码中,我把它变成负面? 在此先感谢!使用moment.js返回负数倒数

var now = moment(); 

var targetDay = now.format("2020-11-03", "dddd, MMMM Do YYYY"); 

var countDown= Math.floor(moment().diff(targetDay, 'seconds')); 

var Days, Minutes,Hours,Seconds; 

    setInterval(function(){ 
    // Updating Days 
    Days =pad(Math.floor(countDown/86400),2); 
    //updating Hours 
    Hours = pad(Math.floor((countDown - (Days * 86400))/3600),2); 
    // Updating Minutes 
    Minutes =pad(Math.floor((countDown - (Days * 86400) - (Hours * 3600))/60),2); 
// Updating Seconds 
    Seconds = pad(Math.floor((countDown - (Days * 86400) - (Hours* 3600) - (Minutes * 60))), 2); 

    // Updation our HTML view 
document.getElementById("days").innerHTML=Days + ' Days'; 
document.getElementById("hours").innerHTML=Hours + ' Hours'; 
document.getElementById("minutes").innerHTML=Minutes+ ' Minutes'; 
document.getElementById("seconds").innerHTML=Seconds + ' Seconds'; 

    // Decrement 
countDown--; 


if(countDown === 0){ 
    countDown= Math.floor(moment().diff(targetDay, 'seconds')); 
} 

},1000); 
    // Function for padding the seconds i.e limit it only to 2 digits 
    function pad(num, size) { 
     var s = num + ""; 
     while (s.length < size) s = "0" + s; 
     return s; 
    } 
+2

您减量在一段时间内没有停止它? –

+0

你的HTML在哪里? – mjw

回答

2

从momentjs文档引用:

默认情况下,瞬间#DIFF将返回向零舍一批 (向下为正数,最多为负) 如果一时比一时早您将传递到 moment.fn.diff,返回值将为负数。

因此,要解决这个问题,你应该使用下面的代码

var now = moment(); 
var targetDay = moment('2020-11-23', 'YYYY-MM-DD'); 
var countDown= Math.floor(targetDay.diff(now, 'seconds')); 

值将是积极的,因为targetDay时刻后您传递的那一刻moment.diff

+0

非常感谢!现在有道理! –