JavaScript Hacks: Add days to a date
If you were googling for a method to add a few days to a given date in JavaScript, you may be running up a blind alley.
As I painfully learnt that there is a simple way to accomplish this. If you are asking what’s so complex about that, here’s how: Subtract 10 days from the current date. Simply put, find today’s date (day of month as in Date().getDate()), subtract 10 from it. If that is less than 0, wrap around the date to the previous month after finding out the number of days in the previous month. Now if the month was January, wrap around to the previous year. etc.. Simple!!
Now that’s a tad bit too much of coding logic for something as simple as that. There has got to be a much simpler way. Isn’t there a dateAdd or dateSub kinda function? Oops.. Sorry. Gotta write that yourself.
But here’s the catch. JavaScript is foolish enough if we know how to outsmart it with its own Date() constructor.
The Date() object has a constructor that accepts parameters in the following format:
var someDate = new Date(iYear, iMonth, iDay);
Now here’s how we subtract 10 days from today’s date:
var today = new Date(); //Get today’s date
var interval = -10; //Setting the interval as a variable to show its applicability
var tenDaysPrior = new Date(today.getYear(), today.getMonth(), today.getDate()-0+interval);
document.write(tenDaysPrior);
And voila! No need to worry about wrapping across months or years or even bother about the number of days in any month. You could even add/subtract months/years in the same fashion. Try adding 60 days to current date. Works?
Another tip as I head off to bed, to find the number of days in any given month, here is a one liner:
var daysInMonth = new Date(iYear, iMonth-0+1, 0).getDate();
Two points to note:
– The Date object’s month runs from 0 through 11. So January would be 0, June would be 5 and December 11. The reason I am adding 1 to iMonth above is not to correct that but to infact get the 0th day of the next month, which automatically rolls back to the previous month’s last day.
Eg: To find the number of days in Feb 2008, we simply find the 0th day of March 2008. Remember that the month number of March is 2 (which coincides with our real world month number of February). I’ll let you use your brains to code that line.
– If you are wondering why I am subtracting 0 in my expressions, remember that JavaScript is not strongly typed. So to avoid ending up 1+1 with 11, I use the -0 to make sure that JavaScript treats them as numbers and not strings. One could also use *1 or /1 to the same effect.
Cheers!