开发者

Calculate the date yesterday in JavaScript

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


[april 2022]: Here is a snippet to extend the Date prototype (without polluting the global namespace)

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


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/


Try this

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


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


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

In your case:

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


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


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

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


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


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


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

will do the trick


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


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


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)


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


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


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


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)


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.


Here are 2 one liners:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜