Coder Perfect

In JavaScript, find the date from yesterday.

Problem

In JavaScript, how can I calculate yesterday as a date?

Asked by Omega

Solution #1

var date = new Date();

date ; //# => Fri Apr 01 2011 11:14:50 GMT+0200 (CEST)

date.setDate(date.getDate() - 1);

date ; //# => Thu Mar 31 2011 11:14:50 GMT+0200 (CEST)

Answered by James Kyburz

Solution #2

[edit sept 2020]: added an arrow function to a snippet including the prior response.

Answered by KooiInc

Solution #3

Surprisingly, no one has mentioned the simplest cross-browser solution.

To find the exact same time as yesterday:

var yesterday = new Date(Date.now() - 86400000); // that is: 24 * 60 * 60 * 1000

*: If your use-case doesn’t mind potential imprecision due to calendar oddities (like daylight savings), this is a good option; otherwise, I’d recommend https://moment.github.io/luxon/.

Answered by Fabiano Soriani

Solution #4

Try this

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

Answered by ashishjmeshram

Solution #5

Use the following formula to generalize the query and perform further diff calculations:

var yesterday = new Date((new Date()).valueOf() - 1000*60*60*24);

This generates a new date object using the value of “now” as an integer, which is the unix epoch in milliseconds minus one day.

Two days ago:

var twoDaysAgo = new Date((new Date()).valueOf() - 1000*60*60*24*2);

An hour ago:

var oneHourAgo = new Date((new Date()).valueOf() - 1000*60*60);

Answered by Ami Heines

Post is based on https://stackoverflow.com/questions/5511323/calculate-the-date-yesterday-in-javascript