Saturday, 13 May 2017

Add number of days to a Date in javascript 0

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);



0 comments:

Post a Comment