views:

1149

answers:

4

Hi All,

I want to find date by subtracting X number of days from a particular date in JavaScript. My JavaScript function accepts 2 parameters. One is the date value and the other is the number of days that needs to be subtracted.

For example, I pass my argument date as 27 July 2009 and i pass my other argument as 3. So i want to calculate the date 3 days before 27 July 2009. So the resultant date that we should get is 24 July 2009. How is this possible in JavaScript. Thanks for any help.

+12  A: 

Simply:

yourDate.setDate(yourDate.getDate() - daysToSubtract);
pianoman
Great Thanks!!!
ajithmanmu
I don't think this will work unless the current day of the month is more than the days you are subtracting.
tvanfosson
... for example it works today with -3 because today is the 27 (in the US, but if today was the 2nd, you'd end up with the new date being -1 and setDate will die if you try to set the day of the month to a negative number.
tvanfosson
@tvanfosson- thanks for noting this point.Bad me....I will try all the methods and get back...
ajithmanmu
@all: This will work for all cases. If setDate gets a negative value then it sets the date back into the previous month as you would hope. This is much easier than subtracting days in milliseconds.
Prestaul
Prestaul is correct. I just did some testing, adding and subtracting over up to one hundred days each way with `setDate()`. It works as expected in all cases, even across month boundaries.
pianoman
@all-This works for me on all cases..Thnx!!
ajithmanmu
+1  A: 

Here's an example, however this does no kind of checking (for example if you use it on 2009/7/1 it'll use a negative day or throw an error.

function subDate(o, days) {
// keep in mind, months in javascript are 0-11
return new Date(o.getFullYear(), o.getMonth(), o.getDate() - days);;
}
OneOfOne
That seems to work too (in Safari at least). I was surprised the accepted answer works. Apparently, it will adjust the month / year to return a valid date: e.g., Date(2009, 6, 0) becomes Date(2009, 5, 30).
Patrick McElhaney
Work in both Firefox and Safari for me, including with negative numbers.
tvanfosson
+2  A: 

This is what I would do. Note you can simplify the expression, I've just written it out to make it clear you are multiplying the number of days by the number of milliseconds in a day.

 var newDate = new Date( yourDate.getTime() - (days * 24 * 60 * 60 * 1000) );
tvanfosson
A: 

Just another option, which I wrote:

DP_DateExtensions Library

It's probably overkill if ALL you want to do is one calculation, but if you're going to do more date manipulation you might find it useful.

Supports date/time formatting, date math (add/subtract date parts), date compare, date parsing, etc.

Jim Davis
I got error while clicking on the link..:-(
ajithmanmu
Seems to be working for me... nothing that I can see in the logs - are you still getting it? What is the error?Thanks.
Jim Davis