JavaScript for getting the previous Monday

后端 未结 7 2121
孤城傲影
孤城傲影 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 05:06

    Thank you @Philippe Dubé-Tremblay for your nice solution (above),

    I will just put here the wrapping function for those who, like me, plan to call this function repeatedly.

    // Accepts a date as parameter or with no parameter will assume the current date.
    const getPreviousMonday = (date = null) => {
      const prevMonday = date && new Date(date.valueOf()) || new Date()
      prevMonday.setDate(prevMonday.getDate() - (prevMonday.getDay() + 6) % 7)
      return prevMonday
    }
    

提交回复
热议问题