Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get "the day before a date" in javascript?

Tags:

javascript

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?

like image 374
Arbiter Avatar asked May 06 '13 15:05

Arbiter


2 Answers

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.

like image 178
Pointy Avatar answered Oct 17 '22 10:10

Pointy


Try this:

var date = new Date('04/28/2013 00:00:00');
var yesterday = new Date(date.getTime() - 24*60*60*1000);
like image 13
Vadim Avatar answered Oct 17 '22 08:10

Vadim