How can I calculate yesterday as a date in JavaScript?
20 Answers
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)

- 13,775
- 1
- 32
- 33
-
31Nice. At first glance, it might seem that this would fail as `getDate` returns the day of the month (eg: 1 - 31) but actually `setDate(0)` sets the date to the last day of the previous month. Does this work across all browsers though? – Drew Noakes Mar 21 '14 at 14:19
-
3Couldn't verify "all" browsers but worked in all I tested https://camo.githubusercontent.com/d9443979594114be925dc586285797773c60adbc/68747470733a2f2f63692e746573746c696e672e636f6d2f6a616d65736b796275727a2f7965737465726461792e706e67 – James Kyburz Mar 24 '14 at 20:57
-
Hmm yes just tested it out directly and you're right, not sure how my use case was different and have since completely refactored away from it. So I won't be able to see. – Zargold Feb 11 '18 at 18:10
-
Doesn't work in MacOS Firefox. Rotates in the current month, as in 2023-01-00 becomes 2023-01-31. – soger Feb 17 '23 at 17:21
[june 2023] Here is a library to manipulate an ES-Date.
[edit sept 2020]: a snippet containing previous answer and added an arrow function.
// 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;
}

- 119,216
- 31
- 141
- 177
-
6I'd prefer to avoid messing with the scope: `var yesterday = (function(d){ d.setDate(d.getDate()-1); return d})(new Date)` – Roy Tinker Nov 22 '13 at 21:41
-
6If you need a one-liner, use something like new Date( Date.now() - 24*60*60*1000 ); this has the benefit of only creating one Date object. But honestly, whoever's maintaining this code will be *much* happier to see the clear 2-line version than they would something throwing functions around (or milliseconds, for that matter). – Rob Whelan Jul 25 '14 at 01:21
-
1I really dig the way you've done this. I already had my solution and then I saw this. I will change my yesterday! I had to slightly alter this answer to add parens to get past code validator: `const yesterday = (d => new Date(d.setDate(d.getDate()-1)).toISOString().split("T")[0])(new Date());`, and I'm just grabbing YYYY-MM-DD (no need to pad to get the date that I'm just using as setting max attribute on date input using the toISOString here). – Neil Gaetano Lindberg Sep 17 '20 at 18:28
-
I got tripped up by this: `const yesterday = d => new Date(d.setDate(d.getDate()-1)` - this mutates the input parameter `d`. So `const now = new Date(); const yest = yesterday(now);` will mutate `now`. – icc97 Dec 02 '22 at 09:29
-
-
@icc97 the [mentioned snippet](https://stackblitz.com/edit/web-platform-bmn16x?file=script.js) now also contains a non destructive method to manipulate a `Date`. – KooiInc Dec 02 '22 at 12:16
-
@KooiInc Now that I know the problem - [I have re-written it](https://stackoverflow.com/a/74653814/327074) :) I was writing the comment as a warning to others. Thank you for updating it though! – icc97 Dec 03 '22 at 15:36
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/

- 8,182
- 9
- 43
- 59
-
16How does this work when daylight savings changes? Wouldn't that bump it ahead / behind an hour? – Adam Tegen Oct 25 '17 at 16:13
-
4It's not a correct answer, since not all days last 24 hours. In countries adopting daylight saving time (e.g. all Europe and most North America), there is one day lasting 23 hours and one 25 hours. – Kar.ma Oct 01 '20 at 07:49
-
2
-
2why comment? This is more clear: `const yesterday = new Date(Date.now() - 24 * 60 * 60 * 1000);` – YakovL Jan 08 '23 at 10:20
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);

- 480
- 7
- 17
-
This seems to be the safest method as we are operating on unix epoch expressed in terms of milliseconds. So the arithmetic is safer than doing something like getDate()-1. I have not tried getDate()-1, but based on the documentation of getDate(), it will return 1 if today's date is 1st of any month. And 1-1 = 0 is not a valid date. Not sure how setDate(0) will work. – Kapil Pendse Jun 27 '14 at 10:21
-
1This was my approach, though you can simplify it a bit as well -- try something like new Date( Date.now() - 24*60*60*1000 ); – Rob Whelan Jul 25 '14 at 01:15
-
setDate(0), btw, would be fine -- it would flip to the last day of the previous month. But it seems tidier (and more intuitive) to drop do the millisecond representation here, to me -- the one downside is that "number of millis in a day" is not as obvious, so it could be easy to mistype that calculation. – Rob Whelan Jul 25 '14 at 01:18
-
Working with unix time seems like the more reliable option. This should be rated higher. – Paul Jan 29 '15 at 08:07
-
Yea, I like this approach the best. There's less ambiguity. I ended up going with `new Date(Date.parse(new Date()) - 86400000)`. Though I do like Date.now() so maybe I'll try that instead. It'll save an extra date. – coblr Aug 18 '15 at 18:18
-
2I'm surprised nobody pointed out that it's not a correct answer, since not all days last 24 hours. In countries adopting daylight saving time (e.g. all Europe and most North America), there is one day lasting 23 hours and one 25 hours. – Kar.ma Oct 01 '20 at 07:48
-
hmm, interesting! @Kar.ma, how would you fix this using plain javascript? Or is this construct working in all edge cases? date.setDate(date.getDate() - 1); The advantage of using my suggested way is that it is easy to generalize to any interval, but you're right that humans mess up the calendar so maybe for seconds, minutes and hours it would still be best to use: new Date((new Date()).valueOf() - 1000*60*60*24); – Ami Heines Oct 01 '20 at 16:19
-
1@AmiHeines You should never multiply for 24, in my opinion. About plain Javascript, yes, `date.setDate(date.getDate() + n)` always works, no need to look for something else. You just need to be sure that `n` is an integer. Of course, the other approach is a good way to go in case of differences in hours or minutes or seconds. – Kar.ma Oct 05 '20 at 11:52
I use moment library, it is very flexible and easy to use.
In your case:
let yesterday = moment().subtract(1, 'day').toDate();
-
2
-
-
2For people using [Dayjs](https://day.js.org/) ```dayjs().add(-1, 'day')``` – Rohit Prasad Jun 28 '20 at 15:17
new Date(new Date().setDate(new Date().getDate()-1))

- 257
- 2
- 4
-
5Might you add a bit of explanation? Plain code blocks alone aren't all that helpful – CertainPerformance Aug 09 '18 at 06:02
-
-
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);

- 8,132
- 2
- 38
- 47
-
2Please remember that not all days last 24 hours. In countries adopting daylight saving time (e.g. all Europe and most North America), there is one day lasting 23 hours and one 25 hours. So, only the first implementation out of these four is fine with this issue. – Kar.ma Oct 01 '20 at 07:51
//Create a date object using the current time
var now = new Date();
//Subtract one day from it
now.setDate(now.getDate()-1);

- 398,270
- 210
- 566
- 880

- 139
- 1
- 1
- 10
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);

- 131
- 1
- 3
d.setHours(0,0,0,0);
will do the trick

- 242,637
- 56
- 362
- 405

- 1,174
- 1
- 17
- 32
-
1Will it? I thought this just set your hours, minutes and seconds to 0, but does not actually change the date? – Jesper Bylund Aug 30 '16 at 07:45
-
1I had to use negative numbers to get to yesterday: `d.setHours(-1,0,0,0)`. This will return yesterday's date, but it may not be the time you want (23:00:00) – cs_pupil Aug 01 '19 at 17:41
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

- 785
- 5
- 13
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

- 77
- 4
-
2Since you are using today.setDate, today will change to yesterday as well. It's better to create yesterday variable and then set it. `var yesterday = new Date(); yesterday.setDate(today.GetDate() - 1)` so you can use both today and yesterday – PersyJack Apr 02 '19 at 19:59
Here are 2 one liners:
new Date(new Date().setHours(-1))
new Date(Date.now() - 86400000)

- 846
- 11
- 18
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)

- 45,213
- 22
- 199
- 169
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()

- 447
- 1
- 4
- 17
"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));

- 11
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);

- 1
- 1
-
Doesn't work, for 2023-01-01 it gives me 2021-12-30. But to be fair none of the other responses work, maybe it's just a MacOS Firefox issue. – soger Feb 17 '23 at 17:40
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)

- 99
- 1
- 2
I wanted something like this answer:
const yesterday = d => new Date(d.setDate(d.getDate() - 1));
The problem is that it mutates d
. So lets keep our mutations hidden inside.
const yesterday = (date) => {
const dateCopy = new Date(date);
return new Date(dateCopy.setDate(dateCopy.getDate() - 1));
}
We can collapse this down to a one-liner expression but it becomes a bit unreadable:
const yesterday = d => new Date(new Date(d).setDate(d.getDate() - 1));
I expanded this out to addDays
and addMonths
functions:
/**
* Add (or subtract) days from a date
*
* @param {Number} days
* @returns {Function} Date => Date + days
*/
const addDays = (days) => (date) =>
new Date(new Date(date).setDate(date.getDate() + days));
/**
* Add (or subtract) months from a date
*
* @param {Number} months
* @returns {Function} Date => Date + months
*/
const addMonths = (months) => (date) =>
new Date(new Date(date).setMonth(date.getMonth() + months));
// We can recreate the yesterday function:
const yesterday = addDays(-1)
// note that `now` doesn't get mutated
const now = new Date();
console.log({ now, yesterday: yesterday(now) })
const lastMonth = addMonths(-1)(now);
console.log({ now, lastMonth })
.as-console-wrapper {
max-height: 100% !important;
}
But by that point you might want to start using date-fns addDays
.

- 11,395
- 8
- 76
- 90