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/

3

3 Answers 3

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" />

Sign up to request clarification or add additional context in comments.

Comments

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/

2 Comments

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.
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.
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" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.