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 date and todays date
Given a date, I need the date of the prior day (the day before). Here's a fiddle with the solution suggested above, and a scenario that doesn't work for me: http://jsfiddle.net/s3dHV/
var date = new Date('04/28/2013 00:00:00');
var yesterday = new Date();
yesterday.setDate(date.getDate() - 1);
alert('If today is ' + date + ' then yesterday is ' + yesterday);
For me, that alerts
If today is Sun Apr 28 2013 00:00:00 GMT-0400 (Eastern Daylight Time) then yesterday is Monday May 27 2013 11:12:06 GMT-0400 (Eastern Daylight Time).
Which is obviously incorrect. Why?
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.
Try this:
var date = new Date('04/28/2013 00:00:00');
var yesterday = new Date(date.getTime() - 24*60*60*1000);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With