Search code examples
javascriptcountdown

Javascript countdown doesn't work in Safari or IE


This function works in Chrome, but not on IE or Safari, what am I doing wrong?

function countdown(){
    var dDay = new Date().getUTCDate() + 1;
    var dMonth = new Date().getUTCMonth() + 1;
    var dYear = new Date().getUTCFullYear();
    var BigDay = new Date(dYear+ ", " +dMonth+ ", " +dDay+ ",00:00:00");
    var msPerDay = 24 * 60 * 60 * 1000;
    var today = new Date();
            var timeLeft = (BigDay.getTime() - today.getTime());

            var e_daysLeft = timeLeft / msPerDay;
            var daysLeft = Math.floor(e_daysLeft);

            var e_hrsLeft = (e_daysLeft - daysLeft)*24;
            var hrsLeft = Math.floor(e_hrsLeft);

            var e_minsLeft = (e_hrsLeft - hrsLeft)*60;
            var minsLeft = Math.floor(e_minsLeft);

            var e_secsLeft = (e_minsLeft - minsLeft)*60;
            var secsLeft = Math.floor(e_secsLeft);
            if(daysLeft.toString().length === 1){
              daysLeft = "0"+daysLeft;
            } 
            if(hrsLeft.toString().length === 1){
              hrsLeft = "0"+hrsLeft;
            } 
            if(minsLeft.toString().length === 1){
              minsLeft = "0"+minsLeft;
            } 
            if(secsLeft.toString().length === 1){
              secsLeft = "0"+secsLeft;
            } 

            timeString = daysLeft + ":" + hrsLeft + ":" + minsLeft + ":" + secsLeft;
            return timeString;     
    }

I use this to print the counter

window.setInterval(function(){
           $('#countdown').html("Time left: "+ countdown());
        }, 1000);

This is the result i get in Chrome:

Time left: 00:01:55:15

And this is the result i get in IE and Safari:

Time left: NaN:NaN:NaN:NaN

Solution

  • I think is because you are building an invalid date object in:

    var BigDay = new Date(dYear+ ", " +dMonth+ ", " +dDay+ ",00:00:00");
    

    Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

    A month is represented:

    Integer value representing the month, beginning with 0 for January to 11 for December.

    You only want to add a day to today, so try change your code in:

    var BigDay = new Date();
    BigDay.setDate(BigDay.getDate() + 1);
    BigDay.setHours(0, 0, 0, 0);
    

    Demo: http://jsfiddle.net/IrvinDominin/HgUhq/