Ich habe den folgenden Code, der mir einfach sagen sollte Unterschied zwischen 2 Monaten, aber alles, was es zurückgibt, ist 1
und ich kann es nicht herausfinden!Unterschied zwischen 2 Daten, sollte funktionieren, aber es ist nicht
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());
bearbeiten
Okay, aktualisiert Code unten:
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();
Und nun die Ausgabe, wie eine der Zahlen negativ und die andere positiv !? Und der Vergleich gegen heute und Termine in der Vergangenheit ...
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)
All ok, Ihr Code denken, dass 2017.02.04 - ist Februar, nicht APRIL :) – KoIIIeY
erste Datum - 1. Januar 2017, die zweite nicht 4. April 2017, ist es der 4. Februar 2017 – KoIIIeY
und so, Feb - 2, Jan - 1, 2-1 = 1 – KoIIIeY