Saturday, 13 May 2017

Add number of days to a Date in javascript 1

Problem:

Add number of days to a Date in javascript / Add number of days to current date in javascript

Solution:

To add number of days to a Date, we need to convert our date string to a date object. Here we are going to use javascript inheritance property (prototype) to do that.

Actual function :

Date.prototype.addDays = function(days){
     return new Date(this.getTime()+days*24*60*60*1000);
 }
In this function we are going to convert days to milliseconds using days*24*60*60*1000 and adding to our date object.

Code usage :

var ourDate = new Date('2014','11','12');
/*for current date just use below line of code instead of above line
var ourDate = new Date();
*/
//Now we are going to add 100 days to our date object.
var futureDate = ourDate.addDays(100);



1 comment:

  1. Weblife Infotech Pvt. Ltd.
    The post is absolutely fantastic! Lots of great information and inspiration both of which we all need! Also like to admire the time and effort you put into your blog. For more info visit.

    ReplyDelete