JavaScript for getting the previous Monday

Tags: ,



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 then the code would make the previous Monday’s date to appear instead (which would be 25-Jan-16).

I have seen some code online:

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

However, this is not quite working, why?

Answer

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)



Source: stackoverflow