2个日期之间的差异,应该有效,但事实并非如此



我得到了以下代码,它应该简单地告诉我两个月之间的区别,但它返回的只是1,我无法计算!

function parseDate(str) {
function pad(s) { return (s < 10) ? '0' + s : s; }
var d = new Date(str);
return d;
}
Array.prototype.monthDifference = function() {
var months = this[1].getMonth() - this[0].getMonth() + (12 * (this[1].getFullYear() - this[0].getFullYear()));
if(this[1].getDate() < this[0].getDate()){
months--;
}
return months;
};
console.log([parseDate('01/01/2017'), parseDate('02/04/2017')].monthDifference());

编辑

好的,请参阅下面的更新代码:

Array.prototype.monthDifference = function() {
console.log((this[1].getMonth()+1) - (this[0].getMonth()+1));
var months = (this[1].getMonth()+1) - (this[0].getMonth()+1) + (12 * (this[1].getFullYear() - this[0].getFullYear()));
if(this[1].getDate() < this[0].getDate()){
months--;
}
return (months > 1) ? 0 : months;
};
[pubDate, new Date()].monthDifference();

现在的输出,一个数字是负数,另一个是正数!?与今天和过去的日期相比。。。

1
Sat Apr 27 1907 00:00:00 GMT+0100 (BST) Wed May 28 1902 00:00:00 GMT+0100 (BST)
-10
Wed Mar 26 1930 00:00:00 GMT+0000 (GMT) Wed May 28 1902 00:00:00 GMT+0100 (BST)
-10
Tue Mar 26 1929 00:00:00 GMT+0000 (GMT) Wed May 28 1902 00:00:00 GMT+0100 (BST)
-10
Tue Mar 26 1929 00:00:00 GMT+0000 (GMT) Wed May 28 1902 00:00:00 GMT+0100 (BST)
-1
Tue Jun 24 1913 00:00:00 GMT+0100 (BST) Wed May 28 1902 00:00:00 GMT+0100 (BST)

这个怎么样?它给出了两个日期之间的天数。

Array.prototype.monthDifference = function() {
var b = this[0].getTime();
var x = this[1].getTime();
var y = x-b;
return Math.floor(y / (24*60*60*1000));
};
var a = [];
a.push(parseDate('01/01/2016'));
a.push(parseDate('02/04/2017'));
console.log(a.monthDifference());

JavaScript Date构造函数不解析英国格式(dd/mm/yyyy)的字符串。您可以拆分日期字符串,然后将其传递到date构造函数中。

工作小提琴:小提琴的日期

function formateDateToUK(dateString){
var splitDate = dateString.split('/'),
day = splitDate[0],
month = splitDate[1] - 1, //Javascript months are 0-11
year = splitDate[2],
formatedDate = new Date(year, month, day);
return formatedDate;
}

函数返回'1',因为这是正确的结果:)

尝试:

console.log([parseDate('01/01/2017'), parseDate('07/01/2017')].monthDifference());

它返回'6'。。。这是正确的。

注意:"new Date(str)"应为"MM/dd/yyyy",而不是"dd/MM/yyyy"。

希望这能帮助

最新更新