Omega
Omega

Reputation: 9158

Calculate the date yesterday in JavaScript

How can I calculate yesterday as a date in JavaScript?

Upvotes: 468

Views: 471477

Answers (16)

KooiInc
KooiInc

Reputation: 122888

Here is a snippet containing previous answer and added an arrow function.

And here is a library I wrote to manipulate instances of JS Date.

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

Upvotes: 156

Griffin
Griffin

Reputation: 851

Here is a one liner that is used to get yesterdays date in format YYYY-MM-DD in text and handle the timezone offset.

// yesterday
new Date(Date.now() - 1 * 864e5 - new Date(Date.now()).getTimezoneOffset() * 6e4).toISOString().split('T')[0];
// 24 hours ago
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())
// yesterday same time
console.log(new Date(Date.now() - 1 * 864e5 - new Date(Date.now()).getTimezoneOffset() * 6e4).toISOString().split('T')[0]); // "2019-11-11"
console.log(new Date(Date.now() - 1 * 864e5 - new Date(Date.now()).getTimezoneOffset() * 6e4).toISOString().split('.')[0].replace('T',' ')); // "2019-11-11 11:11:11"
// 24h ago
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"
// 180 days ago same time
console.log(new Date(Date.now() - 180 * 864e5 - new Date(Date.now()).getTimezoneOffset() * 6e4).toISOString().split('T')[0]); // "2019-05-16"
console.log(new Date(Date.now() - 180 * 864e5 - new Date(Date.now()).getTimezoneOffset() * 6e4).toISOString().split('.')[0].replace('T',' ')); // "2019-05-16 11:11:11"

// that is: [dates] * 24 * 60 * 60 * 1000 - offsetinmin * 60 * 1000    

Upvotes: 4

Fabiano Soriani
Fabiano Soriani

Reputation: 8562

To find exactly the same time yesterday as when you run the function, subtract the number of milliseconds in a day (86400000):

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 Saving Time), otherwise I'd recommend using https://moment.github.io/luxon/

Upvotes: 140

James Kyburz
James Kyburz

Reputation: 14453

var date = new Date();

console.log(date); //# => Fri Apr 01 2011 11:14:50 GMT+0200 (CEST)

date.setDate(date.getDate() - 1);

console.log(date); //# => Thu Mar 31 2011 11:14:50 GMT+0200 (CEST)

Upvotes: 735

Deepu Reghunath
Deepu Reghunath

Reputation: 9653

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>

Upvotes: 14

Sodj
Sodj

Reputation: 959

Here are 2 one liners:

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

Upvotes: 4

icc97
icc97

Reputation: 12783

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.

Upvotes: 0

guyaloni
guyaloni

Reputation: 5862

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

In your case:

let yesterday = moment().subtract(1, 'day').toDate();

Upvotes: 22

Gopinath Radhakrishnan
Gopinath Radhakrishnan

Reputation: 275

new Date(new Date().setDate(new Date().getDate()-1))

Upvotes: 20

John Slegers
John Slegers

Reputation: 47081

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)

Upvotes: 0

Ken Ye
Ken Ye

Reputation: 85

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

Upvotes: 0

Ami Heines
Ami Heines

Reputation: 500

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

Upvotes: 24

godzillante
godzillante

Reputation: 1214

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

will do the trick

Upvotes: 0

gvm
gvm

Reputation: 141

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

Upvotes: 7

Billyhomebase
Billyhomebase

Reputation: 139

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

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

Upvotes: 8

ajm
ajm

Reputation: 13203

Try this

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

Upvotes: 80

Related Questions