I have two specific dates that I need to calculate the duration between in a specific format ${y}year ${w}weeks ${d}days
In order to achieve this, I have created a function. Here is the code snippet:
setTotalDuration(): void {
const formattedFrom = moment(this.startDate).format('YYYY-MM-DD HH:mm:ss');
const formattedTo = moment(this.endDate).format('YYYY-MM-DD HH:mm:ss');
const duration = moment.duration(moment(formattedTo).diff(moment(formattedFrom)));
const y = Math.floor(duration.asYears());
const w = Math.floor(duration.asWeeks() - y * moment().weeksInYear());
const d = Math.floor(duration.asDays() - w * 7);
this.totalDuration = ` ${y}year ${w}weeks ${d}days`;
}
Despite my effort, it seems that the function is not working correctly. For example, when I input startDate as 19/02/2020 and endDate as 19/02/2021, instead of getting the desired result of 1 year 0 weeks 0 days, I am getting 1 year 1 week 373 days. This is not what I intended.
Can anyone help me identify where the issue might be?