15

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
  • 7,720
  • 5
  • 40
  • 66
Shazan
  • 169
  • 1
  • 1
  • 9
  • http://stackoverflow.com/a/4156516/3112803 – gfrobenius Jan 29 '16 at 15:32
  • 2
    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

7 Answers7

46
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
  • 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
14

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
  • 106
  • 1
  • 6
Matthew Lymer
  • 916
  • 6
  • 10
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,689
  • 6
  • 29
  • 60
  • 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
1

Using moment.js:

moment().day("Monday").format('YYYY-MM-DD');
Nagaraj Raveendran
  • 965
  • 13
  • 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
0

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
  • 3,652
  • 25
  • 37
0

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,293
  • 10
  • 18
  • 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
-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
  • 179
  • 1
  • 1
  • 11
  • 1
    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