倒计时器的 Javascript getDate() 方法
在 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
});
});
我有什么想法可以解决这个问题吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这并不是针对您的代码问题的确切解决方案
但如果您想要日期的辅助方法,请查看 sugar.js 它有许多辅助方法,例如轻松计算现在与给定日期之间的天数差异。
查看所有日期方法的功能页面,
您可以使用此函数,例如:
daysFromNow()
已经是daysUntil()
& 的别名。daysSince()
用于计算过去或未来的差异,daysFromNow() 会同时处理过去和未来:)并且该变量将为您提供总天数,即使它是超过 31 天。
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:
daysFromNow()
is already an alias fordaysUntil()
&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.