JavaScript: how to calculate the date that is 2 days ago? [duplicate]
Solution 1:
If you have a date object, you can set it to two days previous by subtracting two from the date:
var d = new Date();
d.setDate(d.getDate() - 2);
console.log(d.toString());
// First of month
var c = new Date(2017,1,1); // 1 Feb -> 30 Jan
c.setDate(c.getDate() - 2);
console.log(c.toString());
// First of year
var b = new Date(2018,0,1); // 1 Jan -> 30 Dec
b.setDate(b.getDate() - 2);
console.log(b.toString());
Solution 2:
You can do the following
var date = new Date();
var yesterday = date - 1000 * 60 * 60 * 24 * 2; // current date's milliseconds - 1,000 ms * 60 s * 60 mins * 24 hrs * (# of days beyond one to go back)
yesterday = new Date(yesterday);
console.log(yesterday);
The Date is available as a number in miliiseconds, you take today subtract two days and create a new date using that number of milliseconds