JavaScript for getting the previous Monday

后端 未结 7 2129
孤城傲影
孤城傲影 2021-02-19 04:03

I would like for the previous Monday to appear in the field where a user enters today\'s date.

E.g.: If today\'s date is entered 29-Jan-16 t

7条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-19 04:52

    Based on @Philippe Dubé-Tremblay answer, i wanted to come up with something that lets you target any previous day:

    let target = 1 // Monday
    let date = new Date()
    date.setDate(date.getDate() - ( date.getDay() == target ? 7 : (date.getDay() + (7 - target)) % 7 ))
    

    This takes into account the previous Monday if today is also Monday

提交回复
热议问题