Pages

3.11.10

Adding Days to Dates in Javascript

There's no built-in function in the Javascript Date object that adds days to an existing date. However, there's a way to make it work by using the Date contructor.

    var date = Date(year, month, day);

Using this constructor, we can acomplish this task. Let's say that we're having a date variable called today and you want to alert a date that is 15 days after this date. The following should do the job.

function displayDates() {
        var today = new Date();
     
        var date = Date(today.getFullYear(), today.getMonth(), today.getDate() + 15);
       
        // Remember that today.getDate()
        function retrieves the days part of the date
     
        alert(date);
    }

Don't worry, if today is October, 25 2010, Javascript will automatically realize that adding 15 days to this date will move us to the next month; November.

In order to make our task a little bit simpler amd more reusable, let's make benifit of the Date's prototype and add a function to the Date objects. Add the following to the same page.

Date.prototype.AddDays =  function(numberOfDays) {
        return new Date(this.getFullYear(), this.getMonth(), this.getDate() + numberOfDays);
    }

This will allow us to easily add days to any date that we make in the future. The following code illustrates how to use it.

function displayDates() {
        var today = new Date();
   
        alert(today.AddDays(5));
    }

To complete the set of functions, add the following as well.

Date.prototype.AddMonths =  function(numberOfMonths) {
        return new Date(this.getFullYear(), this.getMonth() + numberOfMonths, this.getDate());
    }
    
    Date.prototype.AddYears =  function(numberOfYears) {
        return new Date(this.getFullYear() + numberOfYears, this.getMonth(), this.getDate());
    }


Of course, you know that if what we need to do is subtracting days, then we can send a negative numberOfDays value.

No comments:

Post a Comment

Promotional Code for Udemy ServiceNow CIS - HR Practice Tests

If you're planning to become ServiceNow Certified Implementation Specialist - Human Resources (CIS-HR), you can prepare for the exam usi...