To calculate yesterday's date in JavaScript, follow these steps:
- Get the current date.
- Create a new Date object and subtract one day from the current date.
Here is the implementation code:
javascript// Get the current date const today = new Date(); // Display today's date console.log("Today's date is: " + today.toDateString()); // Calculate yesterday's date const yesterday = new Date(today); // Subtract one day yesterday.setDate(yesterday.getDate() - 1); // Display yesterday's date console.log("Yesterday's date is: " + yesterday.toDateString());
This code first creates a Date object for the current date, then modifies the date by using the getDate() and setDate() methods to obtain yesterday's date. Finally, it converts the date to a more readable format using the toDateString() method. This approach is concise and straightforward, suitable for most scenarios requiring the calculation of yesterday's date.
2024年6月29日 12:07 回复