0

r = new Date('Thu Aug 09 2018 22:25:07 GMT+0300');
k = new Date();
k.setDate(r.getDate() + 12);
$('#date_dep').val(k);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="date_dep" />

It works fine, but

var r = new Date('Thu Aug 09 2018 22:25:07 GMT+0300');
var k = new Date();
k.setDate(r.getDate() +12);
document.querySelector('#date_dep').value = k;
<input id="date_dep" readonly size="40">

returns wrong date. 'Thu Aug 09 2018 22:25:07 GMT+0300' is the only way i can get date

http://jsfiddle.net/aq9Laaew/120476/

Robert Moskal
  • 21,737
  • 8
  • 62
  • 86

3 Answers3

2

The problem is that you are making a new Date to add days to instead of adding days to the date you created.

r= new Date('Thu Aug 09 2018 22:25:07 GMT+0300');
k=r;//sets k (the date to be changed) to the date you created above
k.setDate(r.getDate() +12);
$('#date_dep').val(k);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="date_dep" />
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

I fixed your code using moment.js

var r = 'Thu Aug 09 2018 22:25:07 GMT+0300';
var d = moment(r);

k=new Date(d.format());
k.setDate(k.getDate() +12);
$('#date_dep').val(k);

http://jsfiddle.net/aq9Laaew/120508/

Julien
  • 903
  • 7
  • 12
  • 1
    This introduces a library and uses the built-in parser twice for no good reason. Posting the code here as a runnable snippet obviates the use of an external site. – RobG Jul 28 '18 at 22:14
  • I am usually all for moment/lodash/underscore etc but the majority of the cases on stackOverflow you would have to assume that people are `not` using any 3rd party libs. – Akrion Jul 29 '18 at 03:25
0

You can simply achieve this with just one variable. Introducing the k causes confusion and leads to the actual issue.

r = new Date('Thu Aug 09 2018 22:25:07 GMT+0300');
r.setDate(r.getDate() +12);
$('#date_dep').val(r);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="date_dep" />
Akrion
  • 18,117
  • 1
  • 34
  • 54