These two stack overflow questions ask a similar question, but their solution doesn\'t seem to work for me: Javascript Yesterday Javascript code for showing yesterday's
var allmonths = [
'01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'
];
var alldates = [
'01', '02', '03', '04', '05', '06', '07', '08', '09', '10',
'11', '12', '13', '14', '15', '16', '17', '18', '19', '20',
'21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'
];
var today = "2014-12-25";
var aDayBefore = new Date(today);
aDayBefore.setDate(aDayBefore.getDate() - 1);
document.write(aDayBefore.getFullYear()
+ '-' + allmonths[aDayBefore.getMonth()]
+ '-' + alldates[aDayBefore.getDate() - 1]);
Try this:
var date = new Date('04/28/2013 00:00:00');
var yesterday = new Date(date.getTime() - 24*60*60*1000);
You're making a whole new date.
var yesterday = new Date(date.getTime());
yesterday.setDate(date.getDate() - 1);
That'll make you a copy of the first date. When you call setDate()
, it just affects the day-of-the-month, not the whole thing. If you start with a copy of the original date, and then set the day of the month back, you'll get the right answer.