2017-06-20 4 views
-1

Ich habe einen Countdown erstellt, aber es gibt eine negative Ausgabe statt einer positiven zurück. Ich habe nach Gründen gesucht, warum das passiert, aber kein Glück. Weiß jemand, warum ein Countdown negativ sein kann? und wo in meinem Code habe ich es negativ? danke im voraus!Rückgabe eines negativen Countdowns mit 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

Sie Dekrementierung moment.diff in einem Intervall ohne es zu stoppen? –

+0

Wo ist dein HTML? – mjw

Antwort

2

Zitat von momentjs docs:

standardmäßig Moment # diff eine Nummer zurück gerundet auf Null (unten für positive, sich für negativ) Wenn der Moment früher als der Moment ist Sie übergeben an moment.fn.diff, der Rückgabewert wird negativ sein.

Also, dieses Problem zu beheben, sollten Sie den folgenden Code verwenden

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

Wert wird positiv sein, weil targetDay Moment später ist, dass der Moment vorbei sind Sie

+0

vielen dank! macht jetzt Sinn! –