我正在编写一个函数来计算从今天开始的给定日期的天数。 (例如yesterday = 1
,last week = 7
,today = 0
,tomorrow = -1
等等)
看起来很简单,并且使用JavaScript Date()
函数我最初写了这个:
let historicalDate = new Date(2017,05,17).getTime(); // example date: last week
let diff = Math.round((new Date().getTime() - historicalDate) / (24*60*60*1000) );
在得到一些奇怪的结果之后,我整理了代码,但仍然遇到了同样的问题,如下所示:
/**
* Returns an integer, representing the number of days since a given date
**/
function getNumDaysFromDate(historicalDate){
const day = 24*60*60*1000; // The number of milliseconds in one day
const now = new Date().getTime(); // The time right now
const then = historicalDate.getTime(); // The time comparing to
return Math.round((now - then) / day ); // Find difference in milliseconds, then days
}
// Test1: last week, should return 7
let creationDate1 = new Date(2017,05,17);
console.log("Last week:", getNumDaysFromDate(creationDate1)); // Fail, prints -23
// Test2: yesterday, should return 1
let creationDate2 = new Date(2017,05,23);
console.log("Yesterday:", getNumDaysFromDate(creationDate2)); // Fail, prints -29
// Test3: Today, should return 0
let creationDate3 = new Date();
console.log("Today:", getNumDaysFromDate(creationDate3)); // Pass, prints 0
// Test4: day affer tomrrow, should return -2
let creationDate4 = new Date(2017,05,26);
console.log("Future:", getNumDaysFromDate(creationDate4)); // Fail, prints -32

所有上述结果似乎都是大约1个月的结果,(今天的测试3'除外)。
我确定有一个明显或简单的原因,你们中的一个人会立即发现,但我花了最后几个小时的精力!#/ p>
提前致谢!
修改:如果可能的话,我想避免使用像Moment.js这样的库,因为这应该是可能的诞生(?),并且是唯一与日期相关的在我的申请中计算。
答案 0 :(得分:5)
注意:Javascript日期API完全是疯狂的(与Java日期API完全相同)。
月份从0(1月)开始,到11(12月)。所以new Date(2017,5,17)
实际上意味着2017年6月17日。
答案 1 :(得分:-3)
提醒JavaScript中的月份为零(Jan = 0,Feb = 1,...)。所以如果你需要它可能是4(而不是5)。
/**
* Returns an integer, representing the number of days since a given date
**/
function getNumDaysFromDate(historicalDate){
const day = 24*60*60*1000; // The number of milliseconds in one day
const now = new Date().getTime(); // The time right now
const then = historicalDate.getTime(); // The time comparing to
var value = Math.round((now - then) / day );
if(value == 0){
return 0
}
else{
return value+30;
}// Find difference in milliseconds, then days
}
// Test1: last week, should return 7
let creationDate1 = new Date(2017,04,17); // 17th of May 2017
console.log("Last week:", getNumDaysFromDate(creationDate1)); // Fail, prints -23
// Test2: yesterday, should return 1
let creationDate2 = new Date(2017,04,23); // 23 of May 2017
console.log("Yesterday:", getNumDaysFromDate(creationDate2)); // Fail, prints -29
// Test3: Today, should return 0
let creationDate3 = new Date();
console.log("Today:", getNumDaysFromDate(creationDate3)); // Pass, prints 0
// Test4: day affer tomrrow, should return -2
let creationDate4 = new Date(2017,04,26); // 26th of May 2017
console.log("Future:", getNumDaysFromDate(creationDate4)); // Fail, prints -32