Calculate the date yesterday in JavaScript
JavascriptDateJavascript Problem Overview
How can I calculate yesterday as a date in JavaScript?
Javascript Solutions
Solution 1 - Javascript
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 - Javascript
[edit sept 2020]: a snippet containing previous answer and added an arrow function
[edit april 2022]: 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)}`);
.as-console-wrapper {
max-height: 100% !important;
}
Solution 3 - Javascript
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/
Solution 4 - Javascript
Try this
var d = new Date();
d.setDate(d.getDate() - 1);
Solution 5 - Javascript
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 - Javascript
I use moment library, it is very flexible and easy to use.
In your case:
let yesterday = moment().subtract(1, 'day').toDate();
Solution 7 - Javascript
new Date(new Date().setDate(new Date().getDate()-1))
Solution 8 - Javascript
//Create a date object using the current time
var now = new Date();
//Subtract one day from it
now.setDate(now.getDate()-1);
Solution 9 - Javascript
This will produce yesterday at 00:00 with minutes precision
var d = new Date();
d.setDate(d.getDate() - 1);
d.setTime(d.getTime()-d.getHours()*3600*1000-d.getMinutes()*60*1000);
Solution 10 - Javascript
var today = new Date();
var yesterday1 = new Date(new Date().setDate(new Date().getDate() - 1));
var yesterday2 = new Date(Date.now() - 86400000);
var yesterday3 = new Date(Date.now() - 1000*60*60*24);
var yesterday4 = new Date((new Date()).valueOf() - 1000*60*60*24);
console.log("Today: "+today);
console.log("Yesterday: "+yesterday1);
console.log("Yesterday: "+yesterday2);
console.log("Yesterday: "+yesterday3);
console.log("Yesterday: "+yesterday4);
Solution 11 - Javascript
d.setHours(0,0,0,0);
will do the trick
Solution 12 - Javascript
Here is a one liner that is used to get yesterdays date in format YYYY-MM-DD in text and handle the timezone offset.
new Date(Date.now() - 1 * 864e5 - new Date(Date.now() - 1 * 864e5).getTimezoneOffset() * 6e4).toISOString().split('T')[0]
It can obviusly changed to return date, x days back in time. To include time etc.
console.log(Date()) console.log(new Date(Date.now() - 1 * 864e5 - new Date(Date.now() - 1 * 864e5).getTimezoneOffset() * 6e4).toISOString().split('T')[0]); // "2019-11-11" console.log(new Date(Date.now() - 1 * 864e5 - new Date(Date.now() - 1 * 864e5).getTimezoneOffset() * 6e4).toISOString().split('.')[0].replace('T',' ')); // "2019-11-11 11:11:11"
// that is: [dates] * 24 * 60 * 60 * 1000 - offsetinmin * 60 * 1000 // this is: [dates] * 24 * 60 * 60 * 1000 - offsetinmin * 60 * 1000
Solution 13 - Javascript
Give this a try, works for me:
var today = new Date();
var yesterday = new Date(today.setDate(today.getDate() - 1)); `
This got me a date object back for yesterday
Solution 14 - Javascript
If you want to both get the date for yesterday and format that date in a human readable format, consider creating a custom DateHelper
object that looks something like this :
var DateHelper = {
addDays : function(aDate, numberOfDays) {
aDate.setDate(aDate.getDate() + numberOfDays); // Add numberOfDays
return aDate; // Return the date
},
format : function format(date) {
return [
("0" + date.getDate()).slice(-2), // Get day and pad it with zeroes
("0" + (date.getMonth()+1)).slice(-2), // Get month and pad it with zeroes
date.getFullYear() // Get full year
].join('/'); // Glue the pieces together
}
}
// With this helper, you can now just use one line of readable code to :
// ---------------------------------------------------------------------
// 1. Get the current date
// 2. Subtract 1 day
// 3. Format it
// 4. Output it
// ---------------------------------------------------------------------
document.body.innerHTML = DateHelper.format(DateHelper.addDays(new Date(), -1));
(see also this Fiddle)
Solution 15 - Javascript
You can use momentjs it is very helpful you can achieve a lot of things with this library.
Get yesterday date with current timing
moment().subtract(1, 'days').toString()
Get yesterday date with a start of the date
moment().subtract(1, 'days').startOf('day').toString()
Solution 16 - Javascript
"Date.now() - 86400000" won't work on the Daylight Saving end day (which has 25 hours that day)
Another option is to use Closure:
var d = new goog.date.Date();
d.add(new goog.date.Interval(0, 0, -1));
Solution 17 - Javascript
solve boundary date problem (2020, 01, 01) -> 2019, 12, 31
var now = new Date();
return new Date(now.getMonth() - 1 === 0 ? now.getFullYear() - 1 : now.getFullYear(),
now.getDate() - 1 === 0 ? now.getMonth() - 1: now.getMonth(),
now.getDate() - 1);
Solution 18 - Javascript
Fabiano at the number two spot and some others have already shared a similar answer but running this should make things look more obvious.
86400000 = milliseconds in a day
const event = new Date();
console.log(new Date(Date.parse(event) - 86400000))
console.log(event)