开发者

Javascript getDate() Method for a Countdown Timer

开发者 https://www.devze.com 2023-04-06 06:27 出处:网络
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 go

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?


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"
    });
    */ 
//}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消