Calculate the date yesterday in JavaScript
[edit sept 2020]: a snippet containing previous answer and added an arrow function
[april 2022]: Here is a snippet to extend the Date
prototype (without polluting the global namespace)
// a (not very efficient) oneliner
let yesterday = new Date(new Date().setDate(new Date().getDate()-1));
console.log(`Yesterday (oneliner)\n${yesterday}`);
// a function call
yesterday = ( function(){this.setDate(this.getDate()-1); return this} )
.call(new Date);
console.log(`Yesterday (function call)\n${yesterday}`);
// an iife (immediately invoked function expression)
yesterday = function(d){ d.setDate(d.getDate()-1); return d}(new Date);
console.log(`Yesterday (iife)\n${yesterday}`);
// oneliner using es6 arrow function
yesterday = ( d => new Date(d.setDate(d.getDate()-1)) )(new Date);
console.log(`Yesterday (es6 arrow iife)\n${yesterday}`);
// use a method
const getYesterday = (dateOnly = false) => {
let d = new Date();
d.setDate(d.getDate() - 1);
return dateOnly ? new Date(d).toDateString() : d;
};
console.log(`Yesterday (method)\n${getYesterday()}`);
console.log(`Yesterday (method dateOnly=true)\n${getYesterday(true)}`);
// use Date.now
console.log(`Yesterday, using Date.now\n${new Date(Date.now() - 864e5)}`);
.as-console-wrapper {
max-height: 100% !important;
}
Try this
var d = new Date();
d.setDate(d.getDate() - 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)
Surprisingly no answer point to the easiest cross browser solution
To find exactly the same time yesterday*:
var yesterday = new Date(Date.now() - 86400000); // that is: 24 * 60 * 60 * 1000
*: This works well if your use-case doesn't mind potential imprecision with calendar weirdness (like daylight savings), otherwise I'd recommend using https://moment.github.io/luxon/