计算当前日期和另一个日期之间的差异时的错误差异

Wrong difference when calculating the difference between the present day and another date

我需要你的帮助。

在计算当前日期减去另一个日期(英国日期标准)之间的差异时,我的代码没有返回正确的差异值

例如

正确答案应为:

30/01/2015 - 30/01/2015 = 0
30/01/2015 - 29/01/2015 = 1
30/01/2015 - 31/01/2015 = -1

当前代码:

var x = "30/01/2015"
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var today = new Date();
var secondDate = new Date(x);

var diffDays = Math.ceil((secondDate.getTime() - today.getTime())/(oneDay));

alert(diffDays)

您的日期字符串变量 x 格式错误。

来自Date object description

的构造函数参数部分

dateString

String value representing a date. The string should be in a format recognized by the Date.parse() method (IETF-compliant RFC 2822 timestamps and also a version of ISO8601).

使用

var x = '2015-01-30'

JSFiddle for your case.

new Date("30/01/2015").toSTring() 将 return“2017 年 6 月 1 日星期四 00:00:00 GMT+0200(CEST)”。

您传递的日期字符串格式必须是 http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15 or https://www.rfc-editor.org/rfc/rfc2822#page-14

也可以这样说new Date(2015,0,30);

更多信息在这里:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date