0

你能帮我一个函数接收一个参数,即日历日期(12.4.2020)并返回两个代表星期一和星期日日期的日期(11.30.2020 - 12.06.2020)。

到目前为止我所拥有的是:

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

但现在我被阻止了。我不知道如何继续。

谢谢!

4

1 回答 1

0

您可以创建 2 个返回 firstDayOfWeek 和 lastDayOfWeek 之类的函数

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
}

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
}

现在你可以调用这些函数

let lastMonday = firstDayOfWeek(new Date(), 1)
let nextSunday = lastDayOfWeek((new Date(), 7)
于 2020-12-04T07:59:39.570 回答