我正在编写一个接受未来日期的函数,并返回"X weeks, Y days, Z hours"
形式的字符串,表示该日期的倒计时。我的方法是:
weeks
,并将seconds
重新定义为余数(这是Ruby' divmod
所做的事情。)days
,hours
和minutes
执行相同的操作。首先我在Ruby中编写了它,它可以工作:
def time_countdown(*date_string)
seconds = Time.new(*date_string).to_i - Time.now.to_i
weeks, seconds = seconds.divmod 604800
days, seconds = seconds.divmod 86400
hours, seconds = seconds.divmod 3600
minutes, seconds = seconds.divmod 60
return "#{weeks} weeks, #{days} days, #{hours} hours."
end
我使用相同的方法将其翻译为JavaScript,但以下内容除外:
divmod
,我手动执行此操作,首先设置weeks
/ days
/ hours
,然后将seconds
设置为余数。< / LI>
Math.floor
因为JavaScript专门使用浮点数。代码是:
function timeCountdown(epochTime) {
var seconds = epochTime/1000 - new Date().getTime() / 1000;
var weeks = Math.floor(seconds / 604800);
seconds = seconds % 604800;
var days = Math.floor(seconds / 86400);
seconds = seconds % 86400;
var hours = Math.floor(seconds / 3600);
seconds = seconds % 3600;
return weeks + " weeks, " + days + " days, " + hours + " hours.";
}
对于日期2015,6,19
,截至6月1日,JS提供"6 weeks, 5 days, 21 hours"
,Ruby提供"2 weeks, 3 days, 6 hours"
。我无法弄清楚这种差异出现的原因。有人可以指出我的错误吗?
答案 0 :(得分:2)
然而,如果我将日期2015,6,19提供给两个函数,那就是6月1日我写这个,JS告诉我6周,5天,21个小时,Ruby告诉我2周,3天,6个小时
你还没有表明你是怎么做的,但我猜你正在做的事情:
timeCountdown(new Date(2015, 6, 19));
...但在JavaScript中,月份数字从0开始,而不是1,因此6月是5月,而不是6:
timeCountdown(new Date(2015, 5, 19));
// --------------------------^
示例:强>
function timeCountdown(epochTime) {
var seconds = epochTime/1000 - new Date().getTime() / 1000;
var weeks = Math.floor(seconds / 604800);
seconds = seconds % 604800;
var days = Math.floor(seconds / 86400);
seconds = seconds % 86400;
var hours = Math.floor(seconds / 3600);
seconds = seconds % 3600;
return weeks + " weeks, " + days + " days, " + hours + " hours.";
}
snippet.log("July 19th: " + timeCountdown(new Date(2015, 6, 19)));
snippet.log("June 19th: " + timeCountdown(new Date(2015, 5, 19)));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>