Search This Blog

Friday, May 10, 2013

JavaScript dataAdd function

One of the few gifts to programming contributed by the BASIC language is the dateAdd function.
I have seen versions of it ported to Oracle PL/SQL, SQL Server TSQL, PHP and other languages.
Javascript is an obvious candidate for this.
Like many languages, Javascript has a date object and you can easily add a required number of days to it, (this is how date additions are handled in Oracle SQL).
However what you want is to be able to easily and reliably add different periods - weeks, months, years a date add function specifying the interval.
There are various examples - here, and here and even here, the problem with these is that they don't add months correctly.
If you add 1 month to the 31st of January - e.g.var d = new Date ('31/01/2007');d.dateAdd('m', 1);
The code suggested is:

case "m": dTemp.setMonth(dTemp.getMonth() + iNum); break;

This is logical but as January has 31 days and February has (usually) 28, it appears the setMonth function increments the date by the length of the current month.
I had to implement an invoicing function, and accounts people tend to be very particular about their dates.
My suggestion for a month add algorithm is:

The logic handles wrapping around a year by extracting the month and year (also the day which I didn't think I needed).

This is better, but still not correct. When adding one month to 31st of January, we will get the 3rd of March. This is because the new day is 31st of February, which is then wraps over into March.
We need to know how many days are in the next month and adjust accordingly.