2017-06-20 3 views
-1

カウントダウンを作成しましたが、正の値ではなく負の値が返されます。私はこれがなぜ起こるのか理由を研究したが、運がない。カウントダウンがマイナスになる理由は誰にも分かりますか?私のコードのどこに私はそれを否定しましたか?ありがとうございます。 momentjsドキュメントから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

あなたの減少をmoment.diffすること後であるため、正となりますそれを止めることなく、ある間隔で? –

+0

あなたのHTMLはどこですか? – mjw

答えて

2

引用:デフォルトで

モーメントが瞬間より前の場合、モーメント#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モーメントは、あなたが渡している瞬間は

+0

ありがとう!今や意味をなさない! –

関連する問題