Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 823
Shazan Avatar asked Jan 29 '16 15:01

Shazan


People also ask

How do I get the current day of the week in JavaScript?

Call the getDay() method on the Date object to get the day of the week. The getDay method returns the day of the week for the specific date, represented as an integer between 0 and 6 , where 0 is Sunday and 6 is Saturday.

How do I get last week in JavaScript?

To get last week's date, use the Date() constructor to create a new date, passing it the year, month and the day of the month - 7 to get the date of a week ago. Copied! function getLastWeeksDate() { const now = new Date(); return new Date(now.

How do I get the next day in JavaScript?

Using setDate() passing the result of <today>. getDate() + 1 , you'll set the day as “tomorrow”.

What is date () JavaScript?

Date methods allow you to get and set the year, month, day, hour, minute, second, and millisecond of date objects, using either local time or UTC (universal, or GMT) time.


3 Answers

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.

like image 70
Philippe Dubé-Tremblay Avatar answered Sep 24 '22 01:09

Philippe Dubé-Tremblay


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)

like image 25
Matthew Lymer Avatar answered Sep 26 '22 01:09

Matthew Lymer


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

like image 34
Matt Fiocca Avatar answered Sep 26 '22 01:09

Matt Fiocca