Can you help me with a function that receive a parameter which is the calendaristic date(12.4.2020) and returning me two dates that represent dates of monday and sunday(11.30.2020 - 12.06.2020).

What i have until now is:

function getWeek(d){
 findDayOfWeek = new Date(d).getDay(); // for exemple if d is 12.04.2020 that line will return 5 that mean friday
}

but now i'm blocked. I don't know how to continue that.

Thank you!

1

There are 1 best solutions below

0
On

You can create 2 functions which return firstDayOfWeek and lastDayOfWeek like

function firstDayOfWeek(dateObject, firstDayOfWeekIndex) {

    const dayOfWeek = dateObject.getDay(),
        firstDayOfWeek = new Date(dateObject),
        diff = dayOfWeek >= firstDayOfWeekIndex ?
            dayOfWeek - firstDayOfWeekIndex :
            6 - dayOfWeek

    firstDayOfWeek.setDate(dateObject.getDate() - diff)
    firstDayOfWeek.setHours(0,0,0,0)

    return firstDayOfWeek
}

and

function lastDayOfWeek(dateObject, lastDayOfWeekIndex) {

    const dayOfWeek = dateObject.getDay(),
        lastDayOfWeek = new Date(dateObject),
        diff = dayOfWeek <= lastDayOfWeekIndex ?
            dayOfWeek - lastDayOfWeekIndex :
            6 - dayOfWeek

    lastDayOfWeek.setDate(dateObject.getDate() - diff)
    lastDayOfWeek.setHours(0,0,0,0)

    return lastDayOfWeek
}

now you can call these functions

let lastMonday = firstDayOfWeek(new Date(), 1)
let nextSunday = lastDayOfWeek((new Date(), 7)