I have seen a number of posts and talk about the easiest and best way to add days to a JavaScript date object. Most answers recommend the .setDate() method but I have personally found this to be unreliable at times. More so when working on projects where the target audience will be using legacy versions of IE as their primary browser.

Though some will say this is not required my preferred method for doing day adjustment when working with JavaScript dates is to use the following simple function that replicates the functionality of the .setDate() method. It simply generates a new date object based on the original date with the day of the month offset by the number of days passed in (positive or negative).

This keeps things simple and makes for fairly reliable and readable code. By creating the date this way, the month and year adjust themselves based on the day of the month used. Thus if it is a negative number it will go to previous months and potentially years and the inverse for larger positive numbers.

Like this post? Share it!