0

I am trying to get the difference between two dates in Years, months, days. I've tried everything I know so far but so far I am not getting what I was tending to get.

This is my last try, the problem with it is that I am getting 5 years converted into months and days instead of getting the difference in years left, months left and days,

button.addEventListener('click',()=>{

 let m = moment(selectDate.value);
 let applyingDate = m.add(5,"years");
 let cur = moment();
 let diff = applyingDate - cur;
 let years = Math.floor(diff/(1000*60*60*24)/365);
 let months = Math.floor(diff/(1000*60*60*24)/365/12);
 let days = Math.floor(diff/(1000*60*60*24)/30);


console.log(years,months,days);
});

any help, please ? An explanation of the concept would be so much appreciated <3

1 Answers1

0

Looks like you are already using moment.js, I suggest you take a look at their durat section on the docs as it provides a very nice way to do what you need.

For your use case, I believe this solves your problem:

let m = moment(selectDate.value);
let applyingDate = m.add(5,"years");
let cur = moment();

const diffDuration = moment.duration(applyingDate.diff(cur))

return [
  diffDuration.years(),
  diffDuration.months(),
  diffDuration.days()
]

It's very similar to this fiddle I created

Carlos R.
  • 251
  • 3
  • 8
  • yes but what i want is something like (period left : 2 years, 5 months and 3 days ), this is the format I want, the code above return the period of 5 years and convert it to months and days , and that is not what I am looking for thank you – Khaled Berhane Jun 28 '21 at 04:31
  • @KhaledBerhane I edited the answer to match what I believe is your use case. In case it's not, can you please provide the input and the expected output? – Carlos R. Jun 28 '21 at 05:06