Calculate the date yesterday in JavaScript

Calculate the date yesterday in JavaScript

How can I calculate yesterday as a date in JavaScript?


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)

Solution 2:

Not very efficient, but as oneliner:

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

The above creates three Date objects which is needlessly wasteful. This can be reduced to a single instantiation with:

var yesterday = (function(){this.setDate(this.getDate()-1); return this})
                  .call(new Date)

Or, if you prefer:

var yesterday = (function(d){ d.setDate(d.getDate()-1); return d})(new Date)

Or, if you prefer ES6 with arrow function:

let yesterday = ( d => new Date(d.setDate(d.getDate()-1)) )(new Date);

Solution 3:

Try this

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

Solution 4:

Surprisingly no answer point to the easiest cross browser solution

To find exactly the same time yesterday:

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

That is if you wanna go dependency free, otherwise I’d recommend using

Related:  How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'?

Solution 5:

To generalize the question and make other diff calculations use:

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

this creates a new date object based on the value of “now” as an integer which represents the unix epoch in milliseconds subtracting 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);

Solution 6:

//Create a date object using the current time
var now = new Date();

//Subtract one day from it