Two Dates in The Same Week
Matt Ellen-Tsivintzeli

Matt Ellen-Tsivintzeli @mellen

About: Ultra-fullstack software developer. Python, JavaScript, C#, C.

Location:
Earth
Joined:
May 2, 2017

Two Dates in The Same Week

Publish Date: Sep 6 '21
6 0

Have you ever wondered if two dates are in the same week? I have. So I wrote this function to detect such an event.

Enjoy!

function areSameWeeks(date1, date2, boundaryDay=0)
{
    if(date1 > date2)
    {
        let t = date1;
        date1 = date2;
        date2 = t;
    }

    if(((((date2 - date1)/1000)/3600)/24)>6)
    {
        return false;
    }

    let day1 = date1.getUTCDay();
    let day2 = date2.getUTCDay();

    if(day1 == boundaryDay)
    {
        return true;
    }

    if(day2 == boundaryDay)
    {
        return false;
    }

    let d1BoundaryDist = ((day1-boundaryDay)+7)%7;
    let d2BoundaryDist = ((day2-boundaryDay)+7)%7;

    if(d1BoundaryDist <= d2BoundaryDist)
    {
        return true;
    }

    return false;
}
Enter fullscreen mode Exit fullscreen mode

Comments 0 total

    Add comment