To get the yesterday date in Angular you can take help of the getDate()
and setDate()
methods. The getDate()
method gives you the day of month while the setDate()
method sets the day of month of the given date object.
So, to get the yesterday date, you have to first get the today’s day of the month using the getDate()
method and subtract it by -1. Then you have to pass it to the setDate()
method to get the yesterday date.
Here is the full code you need:
const todayDate = new Date(); // Gives today's date const yesterdayDate = new Date(); // Gives today's date const todaysDayOfMonth = todayDate.getDate(); // Gives day of the month yesterdayDate.setDate(todaysDayOfMonth - 1); // Gives yesterday's date console.log(yesterdayDate); // Prints yesterday's date // Eg: Wed Aug 03 2022 22:13:26 GMT+0530 (India Standard Time) console.log(yesterdayDate.toDateString()); // Prints yesterday's date in date format // Eg: Wed Aug 03 2022
This method can give you any previous date you want.
For example, if you want to get 5 days back date, you have to simply subtract -5 instead of -1. The rest of the code will remain exactly the same:
todayDate.setDate(todaysDayOfMonth - 5); // Gives 5 days back date