Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding days to given date in jQuery [duplicate]

Tags:

jquery

date

I have a form with three fields, "start_date", "days", "end_date". I would like to get the end date by adding days to the start date.

My jQuery code is:

$("#days").change(function(){
  var start_date = new Date($("#start_date").attr('value'));
  var days = parseInt($("#days").attr('value'))-1;
  var end_date = new Date(start_date);
  end_date.setDate(start_date.getDate() + days);                            
  $("#end_date").val(end_date.getFullYear() + '-' + ("0" + (end_date.getMonth() + 1)).slice(-2) + '-' + ("0" + end_date.getDate()).slice(-2));
});

In the "end_date" field I get "NaN-aN-aN".

What am I doing wrong?

like image 881
Cosmin Avatar asked May 25 '14 10:05

Cosmin


1 Answers

NaN stands for Not a Number - This means that the users input is invalid.

You could check to see if the input is valid by using if(!isNaN(date.getTime())){

Some code to get you started:

;(function($, window, document, undefined){
    $("#days").on("change", function(){
       var date = new Date($("#start_date").val()),
           days = parseInt($("#days").val(), 10);

        if(!isNaN(date.getTime())){
            date.setDate(date.getDate() + days);

            $("#end_date").val(date.toInputFormat());
        } else {
            alert("Invalid Date");  
        }
    });


    //From: http://stackoverflow.com/questions/3066586/get-string-in-yyyymmdd-format-from-js-date-object
    Date.prototype.toInputFormat = function() {
       var yyyy = this.getFullYear().toString();
       var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
       var dd  = this.getDate().toString();
       return yyyy + "-" + (mm[1]?mm:"0"+mm[0]) + "-" + (dd[1]?dd:"0"+dd[0]); // padding
    };
})(jQuery, this, document);

http://jsfiddle.net/MCzJ6/1

Hope this helps.

W

like image 193
William George Avatar answered Nov 14 '22 09:11

William George