How can I calculate yesterday as a date in JavaScript?
This question is related to
javascript
date
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
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)
_x000D_
var today = new Date();_x000D_
var yesterday1 = new Date(new Date().setDate(new Date().getDate() - 1));_x000D_
var yesterday2 = new Date(Date.now() - 86400000);_x000D_
var yesterday3 = new Date(Date.now() - 1000*60*60*24);_x000D_
var yesterday4 = new Date((new Date()).valueOf() - 1000*60*60*24);_x000D_
console.log("Today: "+today);_x000D_
console.log("Yesterday: "+yesterday1);_x000D_
console.log("Yesterday: "+yesterday2);_x000D_
console.log("Yesterday: "+yesterday3);_x000D_
console.log("Yesterday: "+yesterday4);
_x000D_
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);
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 * 86400000 - new Date().getTimezoneOffset() * 60000).toISOString().split('T')[0]
It can obviusly changed to return date, x days back in time. To include time etc.
console.log(Date())_x000D_
console.log(new Date(Date.now() - 1 * 86400000 - new Date().getTimezoneOffset() * 60000).toISOString().split('T')[0]); // "2019-11-11"_x000D_
console.log(new Date(Date.now() - 1 * 86400000 - new Date().getTimezoneOffset() * 60000).toISOString().split('.')[0].replace('T',' ')); // "2019-11-11 11:11:11"_x000D_
_x000D_
// that is: [dates] * 24 * 60 * 60 * 1000 - offsetinmin * 60 * 1000 // this is: [dates] * 24 * 60 * 60 * 1000 - offsetinmin * 60 * 1000
_x000D_
"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);
I use moment library, it is very flexible and easy to use.
In your case:
let yesterday = moment().subtract(1, 'day').toDate();
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);
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 = {_x000D_
addDays : function(aDate, numberOfDays) {_x000D_
aDate.setDate(aDate.getDate() + numberOfDays); // Add numberOfDays_x000D_
return aDate; // Return the date_x000D_
},_x000D_
format : function format(date) {_x000D_
return [_x000D_
("0" + date.getDate()).slice(-2), // Get day and pad it with zeroes_x000D_
("0" + (date.getMonth()+1)).slice(-2), // Get month and pad it with zeroes_x000D_
date.getFullYear() // Get full year_x000D_
].join('/'); // Glue the pieces together_x000D_
}_x000D_
}_x000D_
_x000D_
// With this helper, you can now just use one line of readable code to :_x000D_
// ---------------------------------------------------------------------_x000D_
// 1. Get the current date_x000D_
// 2. Subtract 1 day_x000D_
// 3. Format it_x000D_
// 4. Output it_x000D_
// ---------------------------------------------------------------------_x000D_
document.body.innerHTML = DateHelper.format(DateHelper.addDays(new Date(), -1));
_x000D_
(see also this Fiddle)
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);
Try this
var d = new Date();
d.setDate(d.getDate() - 1);
[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);
// a function call
yesterday = ( function(){this.setDate(this.getDate()-1); return this} )
.call(new Date);
console.log(yesterday);
// an iife (immediately invoked function expression)
yesterday = function(d){ d.setDate(d.getDate()-1); return d}(new Date);
console.log(yesterday);
// oneliner using es6 arrow function
yesterday = ( d => new Date(d.setDate(d.getDate()-1)) )(new Date);
console.log(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(getYesterday());
console.log(getYesterday(true));
_x000D_
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/
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()
d.setHours(0,0,0,0);
will do the trick
Source: Stackoverflow.com