我正在尝试在客户端计算机上本地计算时间以指定某个促销的结束时间。我这样做是通过使用以下代码:
var targetDate = new Date(1442055673000);
var currentDate = new Date;
setInterval(updateTime, 1000);
function updateTime() {
var diff = new Date(targetDate - new Date());
var days = diff.getUTCDay();
var hours = diff.getUTCHours();
var minutes = diff.getUTCMinutes();
var seconds = diff.getUTCSeconds();
console.log(days + " : " + hours + " : " + minutes + " : " + seconds);}
促销活动结束的日期是2015年12月9日,今天是2015年9月9日。无论出于何种原因,差异计算不正确(它表明差异是6天而不是3天)。
答案 0 :(得分:0)
getUTCDay()方法返回指定的星期几 根据世界时的日期,其中0代表星期日。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCDay
您是从日期差异创建日期,这是日期差异的非常糟糕的表示。获得天数,小时数和其余数的最简单方法就是使用整数除法:
var diff = Math.floor(new Date(targetDate - new Date()) / 1000);
var days = Math.floor(diff / (60*60*24));
diff %= 60*60*24;
var hours = Math.floor(diff / (60*60));
diff %= 60*60;
var minutes = Math.floor(diff / (60));
diff %= 60;
var seconds = diff;