DEV Community

Cover image for Two Dates in The Same Week
Matt Ellen-Tsivintzeli
Matt Ellen-Tsivintzeli

Posted on • Originally published at gist.github.com

Two Dates in The Same Week

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

Top comments (0)