在Javascript中,只要我们调用getDate()方法,就会在该月的特定日期返回值1-31。当我在var goal
中指定一个大于31的未来日期时,这会导致我的倒数计时器出现问题,导致倒数计时器输出'12'而不是实际在未来日期之前剩余的天数。
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
});
});
我有什么想法可以解决这个问题吗?
答案 0 :(得分:1)
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"
});
*/
//}
答案 1 :(得分:0)
这不是针对您的代码问题的确切修复 但是如果你想要日期的帮助方法,看看sugar.js它有很多辅助方法,比如很容易计算现在和给定日期之间的天数差异。 看看the features page for all date methods
您可以使用此功能,例如:
var goal = "Sun January 01 2011 00:00:01";
goal = new Date(goal);
var difference = goal.daysFromNow();
daysFromNow()
已经是daysUntil()
&amp;的别名daysSince()
用于计算过去或未来的差异,daysFromNow()会立即处理过去和未来:)
并且该变量将为您提供总天数,即使它超过31天。