乐闻世界logo
搜索文章和话题

How to calculate the date yesterday in JavaScript

1个答案

1

To calculate yesterday's date in JavaScript, follow these steps:

  1. Get the current date.
  2. 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 回复

你的答案