【发布时间】:2012-06-20 03:40:44
【问题描述】:
我正在尝试使用 javascript 进行倒计时。但是,我的倒计时只能计算天、小时、分钟和秒。我还想显示年份和月份。
以下是我的代码:
<script type="text/javascript">
today = new Date();
BigDay = new Date("December 25, 2016");
msPerDay = 24 * 60 * 60 * 1000;
timeLeft = (BigDay.getTime() - today.getTime());
e_daysLeft = timeLeft / msPerDay;
daysLeft = Math.floor(e_daysLeft);
e_hrsLeft = (e_daysLeft - daysLeft) * 24;
hrsLeft = Math.floor(e_hrsLeft);
minsLeft = Math.floor((e_hrsLeft - hrsLeft) * 60);
// $("#countdown").append("There are only<BR> <H4>" + daysLeft + " days " + hrsLeft + " hours and " + minsLeft + " minutes left </H4> Until December 25th 2020<P>");
document.write(daysLeft + " days " + hrsLeft + " hours" + minsLeft + " minutes");
</script>
我想输出:
x 年,y 个月,z 天。
【问题讨论】:
-
我可以告诉你的一件事是,这将无法可靠地跨浏览器工作:
new Date("December 25, 2016")。该字符串的格式不正确。如果您知道日期,则根本不想为此使用字符串;而是:new Date(2016, 11, 25)(几个月运行0-11)。另请注意,您正在成为 The Horror of Implicit Globals 的牺牲品。 (很抱歉没有回答,但我现在没有时间调试整个脚本。) -
非常感谢您的建议。我会遵守的。
-
用 Date 对象方法检查这个答案:stackoverflow.com/a/30679505/7246488
标签: javascript countdown