Jesus
Jesus

Reputation: 475

Get the difference between two dates from Monday to Sunday

I have a simple javascript that calculates weeks between two dates, so every 7 days equals 1 week:

function getWeeksDiff(startDate, endDate) {
  const msInWeek = 1000 * 60 * 60 * 24 * 7;

  return Math.round(Math.abs(endDate - startDate) / msInWeek);
}

It works well, but now I want to change the logic of this. I want to get 1 week on each Monday to Sunday, and no related to 7 days. I.E: today is Nov 23, so 24,25,26,27 should count as a week, then from Nov 28(Monday) to Dec 4(Sunday) should be week 2 if I select any of dates between 28 to 4.

How can I achieve that?

Upvotes: 0

Views: 45

Answers (1)

mrconcerned
mrconcerned

Reputation: 1935

If you want to find the actual weeks between to dates you can use the following:

const week = 7 * 24 * 60 * 60 * 1000;
const day = 24 * 60 * 60 * 1000;

function weekStart(dt) {
    const weekday = dt.getDay();
    return new Date(dt.getTime() - Math.abs(0 - weekday) * day);
}

function weeksBetween(d1, d2) {
    return Math.ceil((weekStart(d2) - weekStart(d1)) / week)+1;
}

in that case it does not matter the number of seven days between them.

I have tested it with your test cases, both seems to be working.

const week = 7 * 24 * 60 * 60 * 1000;
const day = 24 * 60 * 60 * 1000;

function weekStart(dt) {
    const weekday = dt.getDay();
    return new Date(dt.getTime() - Math.abs(0 - weekday) * day);
}

function weeksBetween(d1, d2) {
    return Math.ceil((weekStart(d2) - weekStart(d1)) / week)+1;
}

console.log(weeksBetween(new Date("11/23/2022"), new Date("11/24/2022")));
console.log(weeksBetween(new Date("11/28/2022"), new Date("12/04/2022")));

Upvotes: 1

Related Questions