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?
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.
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.
Using setDate() passing the result of <today>. getDate() + 1 , you'll set the day as “tomorrow”.
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.
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.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With