Eugene Sukh
Eugene Sukh

Reputation: 2737

Get duration between two dates (Moment JS)

I have 2 dates. And need to find duration between them in this format ${y}year ${w}weeks ${d}d

For this I created function. Here is code

 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}d`;
}

it works not correctly, now if I pass for example startDate - 19/02/2020 and endDate - 19/02/2021, I get duration - 1year -1weeks 373d. But I need to get 1year 0weeks 0d

Where is my problem?

Upvotes: 1

Views: 322

Answers (1)

joy08
joy08

Reputation: 9652

I hope this is what you wanted. You could get the difference in years and add that to the initial date; then get the difference in weeks and add that to the initial date again.


var moment = require("moment");

var a = moment(["2021", "02", "20"]);
var b = moment(["2020", "02", "19"]);

var years = a.diff(b, "year");
b.add(years, "years");

var weeks = a.diff(b, "week");
b.add(weeks, "weeks");

var days = a.diff(b, "days");

console.log(years + " years " + weeks + " weeks " + days + " days");


Sandbox: https://codesandbox.io/s/compassionate-bas-fg1c2

Upvotes: 2

Related Questions