Explain Codes LogoExplain Codes Logo

Calculate the date yesterday in JavaScript

javascript
date-manipulation
time-zones
daylight-saving-time
Alex KataevbyAlex Kataev·Jan 19, 2025
TLDR

Get yesterday's date in JavaScript by deducting one day using getDate() and setDate() like so:

var yesterday = new Date(); yesterday.setDate(yesterday.getDate() - 1);

Controlling for time zones and daylight saving time

When manipulating dates in JavaScript, handling time zones and daylight saving time (DST) is vital. The Date object in JS treats time as milliseconds since the Unix Epoch (January 1, 1970 UTC). The Date.now() function offers this timestamp for the present moment.

To get yesterday's date, you might think about simply deducting 86400000 milliseconds (equivalent to a day). However, this approach won't account for changes in DST. So instead, utilize setDate() as shown in the Fast Answer to have JavaScript handle DST shifts for you.

Handling calendar boundaries

The Date object natively handles calendar peculiarities such as changing from the 1st of a month to the last day of the previous month, or moving from 1st January to 31st December of the preceding year. By using getDate() and setDate(), you allow the Date object's arithmetic to manage these edge cases.

Formatting yesterday's date

You can format the date as YYYY-MM-DD employing the toISOString() function and splitting the result, as follows:

var yesterday = new Date(); yesterday.setDate(yesterday.getDate() - 1); var formattedDate = yesterday.toISOString().split('T')[0];

Leveraging libraries for complex date calculations

For intricate date calculations or operations involving multiple time zones and DST-varied times, considering date-centric libraries like Luxon, date-fns or moment.js could be beneficial. They offer a broad range of utilities for manipulating dates and are equipped with intrinsic support for different time zones.

Precision matters

While the method illustrated with our time machine metaphor works in most cases, it is crucial to remember that a simple calculation of 86400000 milliseconds does not always respect the intricacies of DST. On the days when the clock goes forward or backward, the real-time length of the day will not be 24 hours.

When your events are time-sensitive, precision is key. Use our first method shown in the Fast Answer. JavaScript's Date object has built-in logic that corrects for the different lengths of days due to time zone shifts and changes in DST.

One-liner method using IIFE and arrow functions

For developers aiming at a minimalist approach, an Immediately Invoked Function Expression (IIFE) alongside arrow functions offers a compact yet robust solution:

const yesterday = (() => { const d = new Date(); d.setDate(d.getDate() - 1); return d.toISOString().split('T')[0]; })();

This precisely crafted function immediately fires and returns the formatted date, reducing potential side effects in a conserved space.