449

How can I calculate yesterday as a date in JavaScript?

20 Answers 20

715
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)
7
  • 35
    Nice. 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? Mar 21, 2014 at 14:19
  • 5
    Couldn't verify "all" browsers but worked in all I tested camo.githubusercontent.com/… Mar 24, 2014 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, 2018 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, 2023 at 17:21
  • Works for me on macOS Firefox Developer Edition. Maybe they fixed it?
    – Austin
    Sep 6, 2023 at 18:15
154

[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;
}

7
  • 6
    I'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, 2013 at 21:41
  • 6
    If 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, 2014 at 1:21
  • 1
    I 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). Sep 17, 2020 at 18:28
  • 1
    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 2, 2022 at 9:29
  • @icc97: so rewrite it to work with a copy of the given date, i'd say.
    – KooiInc
    Dec 2, 2022 at 11:19
133

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/

4
  • 17
    How does this work when daylight savings changes? Wouldn't that bump it ahead / behind an hour?
    – Adam Tegen
    Oct 25, 2017 at 16:13
  • 4
    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 1, 2020 at 7:49
  • 2
    And don't forget about leap seconds.
    – das-g
    Dec 29, 2020 at 23:00
  • 5
    why comment? This is more clear: const yesterday = new Date(Date.now() - 24 * 60 * 60 * 1000);
    – YakovL
    Jan 8, 2023 at 10:20
76

Try this

var d = new Date();
d.setDate(d.getDate() - 1);
1
  • 2
    Next command d.setHours(19,59); To set the time to 7:59PM Jun 3, 2014 at 11:54
23

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);
8
  • 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. Jun 27, 2014 at 10:21
  • 1
    This 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, 2014 at 1: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, 2014 at 1:18
  • 3
    I'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 1, 2020 at 7:48
  • 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 5, 2020 at 11:52
21

I use moment library, it is very flexible and easy to use.

In your case:

let yesterday = moment().subtract(1, 'day').toDate();
3
  • 2
    you'd better use subtract instead of add May 10, 2018 at 8:47
  • Works fine too! Nice job for ng FullCalendar and his validRange
    – XenoX
    Oct 16, 2018 at 10:18
  • 2
    For people using Dayjs dayjs().add(-1, 'day') Jun 28, 2020 at 15:17
20
new Date(new Date().setDate(new Date().getDate()-1))
3
  • 5
    Might you add a bit of explanation? Plain code blocks alone aren't all that helpful Aug 9, 2018 at 6:02
  • Works fine ! Thank you
    – XenoX
    Oct 16, 2018 at 10:15
  • The nice thing about this is that it is immutable
    – icc97
    Dec 2, 2022 at 9:44
13

Using Javascript

var today = new Date();
var yesterday1 = new Date(today.setDate(new Date().getDate() - 1));
var yesterday2 = new Date(today - 86400000);
var yesterday3 = new Date(Date.now() - 1000*60*60*24);
var yesterday4 = new Date(today.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);

Using Moment

var today = moment();
var yesterday = today.subtract(1, 'day').format('DD MMM YYYY');
console.log("Yesterday :",yesterday);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

1
  • 2
    Please 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 1, 2020 at 7:51
8
//Create a date object using the current time
var now = new Date();

//Subtract one day from it
now.setDate(now.getDate()-1);
7

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

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

3
d.setHours(0,0,0,0);

will do the trick

2
  • 1
    Will it? I thought this just set your hours, minutes and seconds to 0, but does not actually change the date? Aug 30, 2016 at 7:45
  • 1
    I 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 1, 2019 at 17:41
2

Here are 2 one liners:

new Date(new Date().setHours(-1))
new Date(Date.now() - 86400000)
1

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

1
  • 2
    Since 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 2, 2019 at 19:59
0

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)

0

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()

0

"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));
0

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
  • 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, 2023 at 17:40
0

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)

0

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.