-1

i have got the following code which should simply tell me difference between 2 months, however all that it is returning is 1 and I can't figure it out!

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());

Edit

Okay, see updated code below:

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();

And now the output, how is one of the numbers negative and the other positive!? And comparing against today and dates in the past...

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)
Martyn Ball
  • 4,679
  • 8
  • 56
  • 126

3 Answers3

1

What about this ? It gives days between two date.

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());
Nezih
  • 381
  • 6
  • 19
1

The JavaScript Date constructor doesn't parse strings in UK format(dd/mm/yyyy). You can split the date string and and then pass it into Date constructor.

Working fiddle: Date foramte fiddle

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;
 }
0

you functions returns '1', since it is the correct result :)

try:

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

and it returns '6'... which is correct.

Note: 'new Date(str)' expects "MM/dd/yyyy" not "dd/MM/yyyy".

Hope this helps

Martin Ackermann
  • 884
  • 6
  • 15