JavaScript for getting the previous Monday

Using moment.js:

moment().day("Monday").format('YYYY-MM-DD');

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)


var prevMonday = new Date();
prevMonday.setDate(prevMonday.getDate() - (prevMonday.getDay() + 6) % 7);

I am a little late but I like this solution. It's a one liner and not that complicated. Making a function for that seems overkill to me.


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