Shazan
Shazan

Reputation: 319

JavaScript for getting the previous Monday

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?

Upvotes: 30

Views: 33854

Answers (11)

Lars Munkholm
Lars Munkholm

Reputation: 308

I could not get the accepted answer to work, and I needed something that can get any day, not just Monday.

I ended up with this

function getPreviousDay(dayOfWeek: number) {
    const todayDate = new Date();
    const todayDay = todayDate.getDay();
    const previousDay = new Date();
    if (todayDay === dayOfWeek) {
        previousDay.setDate(todayDate.getDate() - 7);
        return previousDay;
    }
    const subtract = todayDay > dayOfWeek ? todayDay - dayOfWeek : (7 - (dayOfWeek - todayDay));
    previousDay.setDate(todayDate.getDate() - subtract);
    return new Date(previousDay);
}

Upvotes: 0

Francisco Cortes
Francisco Cortes

Reputation: 1216

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

Upvotes: 0

Zeki Kral
Zeki Kral

Reputation: 35

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)));

Upvotes: 0

user12489349
user12489349

Reputation:

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!

Upvotes: 0

Matthew Lymer
Matthew Lymer

Reputation: 977

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)

Upvotes: 20

Matt Fiocca
Matt Fiocca

Reputation: 1598

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

Upvotes: 6

antoni
antoni

Reputation: 5546

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
}

Upvotes: 2

Nagaraj Raveendran
Nagaraj Raveendran

Reputation: 1210

Using moment.js:

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

Upvotes: 3

Sudeep Devkota
Sudeep Devkota

Reputation: 209

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);

Upvotes: -1

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.

Upvotes: 84

gfrobenius
gfrobenius

Reputation: 4067

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

Upvotes: 1

Related Questions