In this article you will learn that how you can get date of last week with different ways and formats.
To get last week's date, use the Date()
constructor to create a new date and pass it the year, month, and day of the month - 7 to get a date from a week ago.
The getFullYear()
method returns the year of the specified date according to local time.
The getMonth()
method returns the month in the specified date according to local time.
The getDate()
method returns the day of the month for the specified date according to local time.
function getLastWeek() {
var today = new Date();
var lastWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 7);
return lastWeek;
}
// get last week date at same day.
getLastWeek();
How to get date in JavaScript in formatted way. We will use string concatenate logic to convert date object in formatted form
var lastWeek = getLastWeek();
var lastWeekMonth = lastWeek.getMonth() + 1;
var lastWeekDay = lastWeek.getDate();
var lastWeekYear = lastWeek.getFullYear();
var lastWeekDisplay = lastWeekMonth + "/" + lastWeekDay + "/" + lastWeekYear;
console.log(lastWeekDisplay);
How to get date in JavaScript in formatted way with leading zero. We will use slice()
logic to convert date object in formatted string
var lastWeekDisplayPadded = ("00" + lastWeekMonth.toString()).slice(-2) + "/" + ("00" + lastWeekDay.toString()).slice(-2) + "/" + ("0000" + lastWeekYear.toString()).slice(-4);
console.log(lastWeekDisplayPadded);