JavaScript for getting the previous Monday

后端 未结 7 2123
孤城傲影
孤城傲影 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
    }
    
    0 讨论(0)
提交回复
热议问题