Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add days to date using Javascript

I am trying to add days to a given date using Javascript. I have the following code:

function onChange(e) {
    var datepicker = $("#DatePicker").val();
    alert(datepicker);
    var joindate = new Date(datepicker);
    alert(joindate);
    var numberOfDaysToAdd = 1;
    joindate.setDate(joindate + numberOfDaysToAdd);
    var dd = joindate.getDate();
    var mm = joindate.getMonth() + 1;
    var y = joindate.getFullYear();
    var joinFormattedDate = dd + '/' + mm + '/' + y;
    $('.new').val(joinFormattedDate);
}

On first alert I get the date 24/06/2011 but on second alert I get Thu Dec 06 2012 00:00:00 GMT+0500 (Pakistan Standard Time) which is wrong I want it to remain 24/06/2011 so that I can add days to it. In my code I want my final output to be 25/06/2011.

Fiddle is @ http://jsfiddle.net/tassadaque/rEe4v/

like image 453
Tassadaque Avatar asked Jun 16 '11 06:06

Tassadaque


3 Answers

Date('string') will attempt to parse the string as m/d/yyyy. The string 24/06/2011 thus becomes Dec 6, 2012. Reason: 24 is treated as a month... 1 => January 2011, 13 => January 2012 hence 24 => December 2012. I hope you understand what I mean. So:

var dmy = "24/06/2011".split("/");        // "24/06/2011" should be pulled from $("#DatePicker").val() instead
var joindate = new Date(
    parseInt(dmy[2], 10),
    parseInt(dmy[1], 10) - 1,
    parseInt(dmy[0], 10)
);
alert(joindate);                          // Fri Jun 24 2011 00:00:00 GMT+0500 (West Asia Standard Time) 
joindate.setDate(joindate.getDate() + 1); // substitute 1 with actual number of days to add
alert(joindate);                          // Sat Jun 25 2011 00:00:00 GMT+0500 (West Asia Standard Time)
alert(
    ("0" + joindate.getDate()).slice(-2) + "/" +
    ("0" + (joindate.getMonth() + 1)).slice(-2) + "/" +
    joindate.getFullYear()
);

Demo here

like image 82
Salman A Avatar answered Oct 29 '22 19:10

Salman A


I would like to encourage you to use DateJS library. It is really awesome!

function onChange(e) {
    var date = Date.parse($("#DatePicker").val()); //You might want to tweak this to as per your needs.
    var new_date = date.add(n).days();
    $('.new').val(new_date.toString('M/d/yyyy'); //You might want to tweak this as per your needs as well.
}
like image 28
Dhruva Sagar Avatar answered Oct 29 '22 20:10

Dhruva Sagar


Assuming numberOfDaysToAdd is a number:

joindate.setDate(joindate.getDate() + numberOfDaysToAdd);
like image 35
RobG Avatar answered Oct 29 '22 20:10

RobG