27

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?

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Shazan
  • 289
  • 1
  • 3
  • 9
  • http://stackoverflow.com/a/4156516/3112803 – gfrobenius Jan 29 '16 at 15:32
  • 3
    Possible duplicate of [Javascript: get Monday and Sunday of the previous week](http://stackoverflow.com/questions/13681702/javascript-get-monday-and-sunday-of-the-previous-week) – Noel Jan 29 '16 at 16:25
  • Or a dup of [get the first day of the week from current date](https://stackoverflow.com/questions/4156434/javascript-get-the-first-day-of-the-week-from-current-date) – James Gentes Nov 07 '18 at 16:02

10 Answers10

79
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.

  • Thanks @Philippe for your nice solution. I've put a wrapping function which accepts a date here https://stackoverflow.com/a/52750444/2012407 for those who are interested – antoni Oct 11 '18 at 00:28
  • 2
    This works as following: add 6 days to `getDay()` (current day of the week, e.g. Friday=5) and the remainder of the division by the number of a week's days (`(5+6)%7=4`) is subtracted from the current's day number (e.g. `29-4=25`). – CPHPython Jan 30 '20 at 14:26
  • The calculation can be `prevMonday.setDate(prevMonday.getDate() - (prevMonday.getDay() || 7) + 1)`. – RobG Apr 06 '22 at 14:26
20

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)

Sagodi97
  • 225
  • 2
  • 9
Matthew Lymer
  • 992
  • 6
  • 10
6

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

Matt Fiocca
  • 1,533
  • 13
  • 21
  • My solution gets the current date if we are monday. So if you want the same maths, replacing the hardcoded 6 by (7-target) should do it. If you want the last monday in that case, I think those maths work : date.setDate(date.getDate() - (date.getDay() + (6 - target) % 7 + 1) – Philippe Dubé-Tremblay Aug 20 '20 at 18:17
  • @Philippe Dubé-Tremblay, nice and simple, however if i try your update, it grabs two weeks ago, instead of this week. Example: if I target 2 (Tuesday) while running this today on a Thursday, your code grabs two Tuesdays ago instead of the Tuesday from the start of this week – Matt Fiocca Aug 20 '20 at 21:58
  • Parenthesis problem I think: date.setDate(date.getDate() - (date.getDay() + 6 - target) % 7 + 1) – Philippe Dubé-Tremblay Aug 21 '20 at 22:09
3

Using moment.js:

moment().day("Monday").format('YYYY-MM-DD');
Nagaraj Raveendran
  • 1,150
  • 15
  • 23
  • If today is Sunday `2020-05-10`, and shouldn't this give `2020-05-11` whereas the expected is, `2020-05-03` – tezz May 06 '20 at 10:45
2

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
}
antoni
  • 5,001
  • 1
  • 35
  • 44
1

Here is a fiddle demonstrating a few different formats: https://jsfiddle.net/umefez2j/3/

function getMonday(d) {
  var m_names = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
  var d = new Date(d);
  var day = d.getDay(),
      diff = d.getDate() - day + (day == 0 ? -6:1); // adjust when day is sunday

  //Use this one to return this format: Mon Jan 25 2016 09:37:51 GMT-0600 (Central Standard Time)
  //return new Date(d.setDate(diff));

  //Use this one to return this format: Mon, 25 Jan 2016
  //monday=new Date(d.setDate(diff)).toUTCString();
  //monday=monday.split(' ').slice(0, 4).join(' ')
  //return monday;

  //Use this one to return this format: 25-Jan-2016
  monday=new Date(d.setDate(diff));
  var curr_date = monday.getDate();
  var curr_month = monday.getMonth();
  var curr_year = monday.getFullYear();
  return curr_date + "-" + m_names[curr_month] + "-" + curr_year;
}

alert(getMonday(new Date()));

//Created with help from:
//http://stackoverflow.com/a/27480352/3112803
//http://stackoverflow.com/a/4156516/3112803
//http://stackoverflow.com/a/27869948/3112803
gfrobenius
  • 3,987
  • 8
  • 34
  • 66
  • I edited the answer to include a third format and to give props to the source that helped generate this. Hope this helps. I see you're new to stackoverflow, if this works for you mark this as the answer please. – gfrobenius Jan 29 '16 at 15:56
0

The above solutions didn't work for me.

In @Philippe Dubé-Tremblay's solution, it will return the same day if today is already monday!

function getPreviousMonday() : Date {
    let date = new Date();
    let day = date.getDay();
    let prevMonday = new Date();
    if(day == 0 || day == 1){
         prevMonday.setDate(date.getDate() - (day + 6));
    }
    else{
        prevMonday.setDate(date.getDate() - (day - 1));
    }
    return prevMonday;
}

OR

 if (day == 1) {
  prevMonday.setDate(date.getDate() - 7);
}
else {
  prevMonday.setDate(date.getDate() - (day + 6) % 7);;
}

This works for me!

0

Here is my code to get the last monday from a given date. If the given date is a monday, it returns the same day. This can be used to get the monday of the week that the date is on

let currDate = new Date();
let lastMonday = new Date();
let daysDiff = currDate.getDay() - 1;
lastMonday.setDate(currDate.getDate() - (daysDiff > 0 ? daysDiff : (daysDiff * -6)));
Zeki Kral
  • 35
  • 2
  • 10
0
//function to find the last monday from a given date
function getPreviousMonday(dateObj){
    // get the year, month and week day from the given date.
    var dayOfWeek = dateObj.getDay();
    var dateObjYear = dateObj.getFullYear()
    var dateObjMonth = dateObj.getMonth()
    var dateObjDate = dateObj.getDate()
    //set the previous monday value as the date given so you can modify it as needed, without taking any minutes into account
    var prevMonday = new Date(dateObjYear,dateObjMonth,dateObjDate)
    // if date of week was sunday
    if(dayOfWeek == 0){
      //substract 6 days from the date given so you get monday from the give date.
      prevMonday.setDate(dateObj.getDate() - 6);
    }else{ //substract dayOfWeek - 1 from the given date
      prevMonday.setDate(dateObj.getDate() - (dayOfWeek-1));
    }
    // return last monday's date from a given date
    return prevMonday;
}

this one takes a given date object and returns the previous monday from that date object. it's an adaptation from the accepted answer as that one didnt actually work for me.

Francisco Cortes
  • 1,121
  • 10
  • 19
-1

The easiest solution is to go back the number of days based on today's date. For example, if today's day(0) is Sunday, you can go back 6 days to find the previous Monday. If Today is Monday, you can go back 7 days. Therefore using a modulo will help you in this scenario simply because the number of days you will need to go back is %7 plus 6. Let me break it down in simple steps.

var today=new Date();

This will give you today's date. Now,

var todaysDay=today.getDay();

This will give you your day starting with zero.

var goBack=today.getDay()%7+6;

Now, declare a new date.

var lastMonday=new Date().setDate(today.getDate()-goBack);

Now, this will give you a numeric date value. Convert it back to Date

var desiredDate=new Date(lastMonday);
Sudeep Devkota
  • 189
  • 1
  • 1
  • 11
  • 2
    This is not correct - if today is Wednesday(3) then you would do `(3 % 7) + 6 = 9`. You do not need to go back 9 days, but instead 2 days. The correct formula is `(3 + 6) % 7 = 2`. I.E. `goBack = (today.getDay() + 6) % 7` – Andrew McOlash Mar 11 '18 at 20:29