JavaScript for getting the previous Monday

后端 未结 7 2090
孤城傲影
孤城傲影 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-19 04:55

    I think your math is just a little off, and I tidied your syntax;

    function getPreviousMonday()
    {
        var date = new Date();
        var day = date.getDay();
        var prevMonday = new Date();
        if(date.getDay() == 0){
            prevMonday.setDate(date.getDate() - 7);
        }
        else{
            prevMonday.setDate(date.getDate() - (day-1));
        }
    
        return prevMonday;
    }
    

    That way you always get the last Monday that happened (which is 7 days ago if today is Monday)

提交回复
热议问题