Asked by Omega
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
[edit sept 2020]: added an arrow function to a snippet including the prior response.
Answered by KooiInc
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
var d = new Date(); d.setDate(d.getDate() - 1);
Answered by ashishjmeshram
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