0

I have a function that add a number of days in a date. But the problem is .setDate is not a function. Here's my code.

$('#term').on('change',function(){
    var datepo = Aug-10-2016
    var days = 35
    var po_date = $.datepicker.formatDate('yy-m-d', new Date(datepo));
    po_date.setDate(po_date + parseInt(days)) 

    alert(po_date)
})

4 Answers4

1

setDate expects a Date object https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate

formatDate returns a string https://api.jqueryui.com/datepicker/#utility-formatDate

Try

var strDate = "Aug-10-2016";
strDate = strDate.replace(/-/g, " ");
var datepo = new Date(strDate);
var days = 35;
datepo.setDate(datepo.getDate() + days);
var strFormatedPODate = $.datepicker.formatDate('yy-m-d', new Date(datepo)); 

See CodePen here: http://codepen.io/ssh33/pen/PzXYrB

Stack
  • 348
  • 3
  • 17
0

Try this

$('#term').on('change',function(){
    var datepo = 'Aug-10-2016';
    var date_obj = new Date;
    var days = 35;
    var po_date = $.datepicker.formatDate('yy-m-d', new Date(datepo));

    alert(po_date + ' ' + date_obj.setDate(parseInt(days)));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>

<input id="term" type="text" />
Arif
  • 565
  • 5
  • 19
0

I got the final answer:

$('#term').on('change',function(){
    var datepo = $('#podate').val();
    var days = $('#term option:selected').data('termdays');
    var po_date = new Date($.datepicker.formatDate('M-dd-yy', new Date(datepo)));
    var po = new Date(po_date.setDate(po_date.getDate() + parseInt(days)))
    var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun","Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    var duedate = months[po.getMonth()]+'-'+po.getDate() +'-'+po.getFullYear();
   alert(duedate);
})
0

Here's the Code in Javascript add days into date() with.setDate()

Can be done without Jquery

const date = new Date('2022-02-02');
  
Date.prototype.addDays = function (days) {
    const date = new Date(this.valueOf());
    date.setDate(date.getDate() + days);
    return date;
};


// +5 days added in '2020-12-02'

console.log("long format : " + date.addDays(05));
//"2022-06-09T11:09:13.804Z" it shows the date with zone and time

// for date with time 
console.log("Date & Time : "+ date.addDays(05).toLocaleString());

// for date with time 
console.log("Date  : "+ date.addDays(05).toLocaleDateString());



// You can use toLocaleDateString('en-CA') on Date object
// in yyyy-mm-dd formant
console.log("yyyy-mm-dd formant :"+ date.addDays(05).toLocaleDateString('en-CA'));
 

List of all Local Shortcodes List of All Locales and Their Short Codes?

Salman Shaikh
  • 321
  • 1
  • 10