I have always contended that date math is one of the hardest and simultaneously easiest tasks programmer perform.  It's difficult because as developers, the calendar isn't exactly our friend.  The number of days in the month are not fixed and even the lenth of the year in days is a floating point number.  But it's easy because we get to stand on the shoulders of giants.

There are options here.  First, let's look at vanilla JavaScript (ES5):

Date.prototype.addDays = function(days) {
    var date = new Date(this.valueOf());
    date.setDate(date.getDate() + days);
    return date;
}

var date = new Date();

alert(date.addDays(5));
This code adds the method addDays to the date prototype

Let's examine how this works.  This particular example uses JavaScripts prototype inheritance model to actually add a function to all Date objects.  This means from this point forward in this site or program, the normal JavaScript date object will have an extra method that nobody else's has.

The actual addition simply involves instantiating a date object.  Next, we use date.getDate(), a built-in function on JavaScript's regular date object, then add the number of days to you passed in as an argument.

But adding days is just the tip of the iceberg.  If you're open to using a third-party library, you absolutly MUST check out moment.js.  This library takes all the hassle out of dealing with dates.  Not just adding them, but formatting them, and doing more complicated date manipulations.

Here are a few examples of relative time calculations:

moment("20111031", "YYYYMMDD").fromNow(); // 9 years ago
moment().startOf('day').fromNow();        // 16 hours ago
moment().endOf('day').fromNow();          // in 8 hours
moment().startOf('hour').fromNow();      
Moment JS makes it trivial to manipulate dates to find offsets, like how many days until... Or the actual date, e.g. what will the date be 1200 days from now.

Our original problem can be solved easily with Moment JS.  Here are a few examples:

moment().subtract(10, 'days').calendar(); // 07/31/2020
moment().calendar();                      // Today at 3:43 PM
moment().add(1, 'days').calendar();       // Tomorrow at 3:43 PM
moment().add(3, 'days').calendar();       // Thursday at 3:43 PM
moment().add(10, 'days').calendar();     

Every language needs easy to use date manipulation libraries and we have them both built into the language, and more extensively in third party libraries.


Linux for Web Developers Title Graphic
Do you code the web? You need this course!  Just $29 for solo developers.