计算两个日期之间的天数.出乎意料的结果

Ali*_*cia 1 javascript date node.js

我正在编写一个函数来计算给定日期从今天开始的天数.(例如yesterday = 1,last week = 7,today = 0,tomorrow = -1等等)

看似简单,并使用Date()我最初编写的JavaScript 函数:

let historicalDate = new Date(2017,05,17).getTime(); // example date: last week
let diff = Math.round((new Date().getTime() - historicalDate) / (24*60*60*1000) );
Run Code Online (Sandbox Code Playgroud)

在得到一些奇怪的结果后,我加密了代码,但仍然遇到了同样的问题,如下所示:

/**
* 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
Run Code Online (Sandbox Code Playgroud)

所有上述结果似乎都是大约1个月出来的(除了'测试3',今天).

我确信这有一个明显或简单的原因,你们中的一个人会立刻发现,但我花了最后几个小时的精力充沛!

提前致谢!

编辑:如果可能,我想避免使用像Moment.js这样的库,因为这应该是可能的诞生(?),并且是我的应用程序中唯一与日期相关的计算.

Rol*_*ble 5

注意:Javascript date API完全是疯了(与Java date API完全一样).

月份从0(1月)开始,到11(12月).所以new Date(2017,5,17)实际上意味着2017年6月17日.

  • @RobG:程序员是人类.人类很早就有条件,因为一年中的第一个月是1月(1 = 1月).定义一个违背基本期望的API是疯狂的.这不仅仅是一个理论问题:因为这种疯狂,我看到了无数的错误.不要指望程序员能够处理任何反直觉的API; 相反,设计符合(合理)期望的API. (2认同)