Question

In Javascript whenever we call the getDate() method a value of 1-31 is returned for the particular day of the month. This creates a problem in my countdown timer when I specify a future date in var goal that is greater than 31 which causes the countdown timer to output '12' instead of the number of days that are actually left until the future date.

  function twoDigits(number) {return (number < 10 ? '0' : '') + number};

        var goal = "Sun January 01 2012 00:00:01";
        goal = new Date(goal);
        var now = new Date();
        var count = new Date(goal.getTime() - now.getTime());
        var day = count.getDate() -1;
        var hour = count.getHours()-1; 
        var format = twoDigits(day) + ":" + twoDigits(hour) + ":" + twoDigits(count.getMinutes()) + ":" + twoDigits(count.getSeconds());
      $(function () {
        $('#counter').countdown({
          image: 'digits.png',
          startTime: format
        });
      });

Any ideas how I could fix this?

Was it helpful?

Solution

function padLeft(str,len,char) {
    len=Number(len)||1;
    char=String(char)||" ";
    for(var i=0;i<len;i++)str=char+str;
    return str.substr(str.length-len);
}

//$(document).ready(function() {
    var goal = "Sun January 01 2011 00:00:01";
    goal = new Date(goal);
    var now = new Date();
    var count = goal.getTime() - now.getTime();
    var sign = count/Math.abs(count);
    count = Math.abs(count);
    var days = Math.floor(count/(24*60*60*1000));
    count -= days*24*60*60*1000;
    var hours = Math.floor(count/(60*60*1000));
    count -= hours*60*60*1000;
    var minutes = Math.floor(count/(60*1000));
    count -= minutes*60*1000;
    var secs = Math.floor(count/1000);

    var startTime = days +":"+ padLeft(hours,2,"0") +":"+ padLeft(minutes,2,"0") +":"+ padLeft(secs,2,"0");
    alert(startTime);
    /*
    $("#counter").countdown({
        image: 'digits.png',
        startTime: startTime,
        format: "dd:hh:mm:ss"
    });
    */ 
//}

OTHER TIPS

This is not an exact fix for your code's issue but if you want helper methods for dates, take a look at sugar.js it has a host of helper methods, like easily calculating the difference in days between now and a given date. look at the features page for all date methods

you could use this function for example:

var goal = "Sun January 01 2011 00:00:01";
goal = new Date(goal);
var difference = goal.daysFromNow();

daysFromNow() is already an alias for daysUntil() & daysSince() which are for calculating differences in the past or future, daysFromNow() takes care of the past and future at once :)

and that variable would give you the total amount of days, even if it's more than 31 days.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top