How to get last Monday or last Friday or any last day in JavaScript?
In JavaScript, the date object is very extensive. We can very much get everything using it. In many cases, we need the last weekday from the current date. The weekday can be any day such as Monday, Friday, or any day.
Following is the code to show last Monday from the current date:
Show last Monday
let currentDateObj = new Date(); currentDateObj.setDate(currentDateObj.getDate() - (currentDateObj.getDay() + 6) % 7); console.log(currentDateObj);
Show last Tuesday
let currentDateObj = new Date(); currentDateObj.setDate(currentDateObj.getDate() - (currentDateObj.getDay() + 5) % 7); console.log(currentDateObj);
Show last Wednesday
let currentDateObj = new Date(); currentDateObj.setDate(currentDateObj.getDate() - (currentDateObj.getDay() + 4) % 7); console.log(currentDateObj);
Show last Thursday
let currentDateObj = new Date(); currentDateObj.setDate(currentDateObj.getDate() - (currentDateObj.getDay() + 3) % 7); console.log(currentDateObj);
Show last Friday
let currentDateObj = new Date(); currentDateObj.setDate(currentDateObj.getDate() - (currentDateObj.getDay() + 2) % 7); console.log(currentDateObj);
Show last Saturday
let currentDateObj = new Date(); currentDateObj.setDate(currentDateObj.getDate() - (currentDateObj.getDay() + 1) % 7); console.log(currentDateObj);
Show last Sunday
let currentDateObj = new Date(); currentDateObj.setDate(currentDateObj.getDate() - (currentDateObj.getDay()) % 7); console.log(currentDateObj);