get number of months and remaining days between two dates in javascript? -
this question has answer here:
i'm looking how number of months , remaining days between 2 dates.
example: in = 2017-04-10, out = 2017-05-15
output should 1 month, 5 days
-
this 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 1 month, 35 days.
how can remove days of month if there month, , show remaining days?
here 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 , out = 2017-05-15 let diff1 = getdiff('2017-04-10', '2017-05-15'); console.log('diff1:', getdiffformatted(diff1)); // in = 2017-04-10 , out = 2017-05-09 let diff2 = getdiff('2017-04-10', '2017-05-09'); console.log('diff2:', getdiffformatted(diff2)); // in = 2017-04-10 , out = 2017-06-15 let diff3 = getdiff('2017-04-10', '2017-06-15'); console.log('diff3:', getdiffformatted(diff3)); // in = 2015-01-22 , 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>
Comments
Post a Comment