1

I'm having two dates given below with the format for which I need to get the number of months that are there in between them.I tried Difference in months between dates in Javascript : but the format is not matching with the one that I have.Can anybody suggest a fix please?

 startDate:"2015-09-07",
 endDate: "2015-12-30"

Also I need to display the months that are there in between the dates like:

var months=["sept","oct","nov","dec","jan","feb"]
Community
  • 1
  • 1
forgottofly
  • 2,729
  • 11
  • 51
  • 93

1 Answers1

-1

Well, you could always split string and use month like this:

var startDate = startDate.split("-");
var endDate= endDate.split("-");
var MonthDifference = endDate[1] - startDate[1];

So you could for example do this function:

function DifferenceInMonths(startDate, endDate){
    startDate= startDate.split("-");
    endDate= endDate.split("-");
    return endDate[1] - startDate[1];
}

But then we are facing problem where these dates could happen in 2 different years. What if you would try this:

function differenceCalculatedInMonthsByUnix(startDate, endDate){
startDate = new Date(startDate).getTime();
endDate= new Date(endDate).getTime();
var difference = endDate - startDate;
return timeMe(difference);
}

function timeMe(unix_timestamp){
    unix_timestamp = parseInt(unix_timestamp);
    var date = new Date(unix_timestamp);
    var days = date.getDate();
    var month = date.getMonth() + 1;
    var year = date.getFullYear()
    // hours part from the timestamp
    var hours = date.getHours();
    // minutes part from the timestamp
    var minutes = "0" + date.getMinutes();
    // seconds part from the timestamp
    var seconds = "0" + date.getSeconds();
    // will display time in 10:30:23 format
    var formattedTime = days + '.' + month + '.' + year + ' at:' + hours + ':' + minutes.substr(minutes.length-2) + ':' + seconds.substr(seconds.length-2);
    return (12 * year) + month
}

Not sure did i do that TimeMe() my self or did i find it from stackOverflow so if some one needs credits, pm me. But yea the idea in this is, that we turn date into unix time stamp, calculate difference, and turn it into months.

J0N3X
  • 228
  • 2
  • 14
  • Why should I treat the date as a string and parse it myself when `Date('2015-09-23')` will do it for me? –  Sep 23 '15 at 14:05
  • In about 20% of browsers in use, `new Date(startDate)` will return NaN, so not a good idea. – RobG Sep 23 '15 at 14:05
  • @torazaburo I believe this question is not made by you but since you need help with this, you can see if you'd read the whole text that there is 2 different ways of doing the thing OP wants to do, both having it's own negative ways – J0N3X Sep 23 '15 at 14:12