0

I'm looking for how to get number of months and remaining days between 2 dates.

Example: in = 2017-04-10, out = 2017-05-15

output should be 1 month, 5 days

-

this is what i tried: number of months

var numofmonths = out_month - in_month + (12 * (out_year - in_year));
if(out_day < in_day){
 numofmonths--;
}

and days

var numofdays (end - start) / (1000 * 60 * 60 * 24)

output is like 1 month, 35 days.

how can I remove the days of the month if there is month, and show only remaining days?

Elyor
  • 5,396
  • 8
  • 48
  • 76

1 Answers1

0

Here is a solution using Moment.js:

let getDiff = (inDate, outDate) => {
    let years, months, days;
    
    inDate = moment(inDate);
    outDate = moment(outDate);
    
    years = outDate.diff(inDate, 'year');
    inDate.add(years, 'years');

    months = outDate.diff(inDate, 'months');
    inDate.add(months, 'months');

    days = outDate.diff(inDate, 'days');

    return {
      days: days,
      months: months,
      years: years
    };
  },
  getDiffFormatted = d => `${d.years} years, ${d.months} month, ${d.days} days`;

// in = 2017-04-10 and out = 2017-05-15
let diff1 = getDiff('2017-04-10', '2017-05-15');
console.log('diff1:', getDiffFormatted(diff1));

// in = 2017-04-10 and out = 2017-05-09
let diff2 = getDiff('2017-04-10', '2017-05-09');
console.log('diff2:', getDiffFormatted(diff2));

// in = 2017-04-10 and out = 2017-06-15
let diff3 = getDiff('2017-04-10', '2017-06-15');
console.log('diff3:', getDiffFormatted(diff3));

// in = 2015-01-22 and out = 2017-06-15
let diff4 = getDiff('2015-01-22', '2017-06-15');
console.log('diff4:', getDiffFormatted(diff4));
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46