Get Yesterday's Date in JavaScript or Node.js

Sometimes it’s helpful to translate dates into labels in your web application. For example, the human brain perceives the label „yesterday“ easier than translating the string of yesterday’s date to „yesterday“.

This tutorial shows you how to calculate yesterday’s date in JavaScript.

Node.js Series Overview

How Do You Get Yesterday’s Date in JavaScript

JavaScript ships with a handful of methods to adjust dates. One of those methods is the setDate method allowing you to change the day of a date. Calculating yesterday’s date is subtracting one day from today.

Here’s a sample function calculating yesterday’s date (from now):

/**
 * Returns yesterday‘s date. Basically "now minus one day". Automatically handles month and year changes.
 *
 * @returns {Date}
 */
function yesterday () {  
  const yesterday = new Date()
  yesterday.setDate(yesterday.getDate() - 1)

  return yesterday
}

Also, a nice part of JavaScript’s setDate function is the automatic handling of the month and year changes. For example, when retrieving yesterday on July 1st you’re receiving June 30th. That’s great handling by JavaScript!

yesterday()  
// 2022-06-30T14:40:56.627Z
// at the time of writing this tutorial "new Date()" is "2022-07-01"

Enjoy!

Explore the Library

Find interesting tutorials and solutions for your problems.