Behseini Behseini - 1 month ago 13
Javascript Question

Not Able to Increment Date in Js Date Library

Can you please let me know why I am not able to increment the day by clicking on

+




var dayLength = 1000*3600*24;
var current = new Date();
console.log(current);
$('button').on('click', function(){
var a = new Date((new Date()).valueOf() + dayLength);
console.log(a);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn btn-default">+</button>




Answer

You add dayLength to new Date() which is current date. You should add it to current variable.

  var dayLength = 1000*3600*24;
  var current = new Date();
  console.log(current);

  $('button').on('click', function(){
    current = new Date(current.getTime() + dayLength);
    console.log(current);
   });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn btn-default">+</button>

Note that I also change valueOf to getTime because per docs, valueOf is usually not called in user code.