VikingRock27
VikingRock27

Reputation: 3

Adding days in JavaScript returns crazy values

I am trying to add any amount of days to a given date with this code

$("body").change(".editField", function() {
  var startDate = new Date(Date.now());
  var addedDays = $("#daysAdded").val();
  var calculatedDate = addDays(startDate, addedDays);
  console.log(addedDays);
  console.log(calculatedDate)
  $("#dayResult").val(calculatedDate.toISOString().split("T")[0]);
});
function addDays(date, days) {
  var result = new Date(date);
  result.setDate(result.getDate() + days);
  return result;
};
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<input type='number' id='daysAdded' class='editField'>
<input type='text' id='dayResult'>

Link to JSFiddle: https://jsfiddle.net/gv4qswjf/

The problem - no matter what start date you are putting in:

Plus SUBTRACTION doesn't work at all!

What is going on? I haven't found anything about such problem, but for me it occurs in Chrome, Firefox, Edge...

I also tried different jQuery versions (see code above: 1.12, see JSFiddle: 3.3).

Upvotes: 0

Views: 74

Answers (1)

Saravanan Kandasamy
Saravanan Kandasamy

Reputation: 96

When geting the value of input parse it to Integer using parseInt() this will solve your problem

$("body").change(".editField", function() {
  var startDate = new Date(Date.now());
  var addedDays = parseInt($("#daysAdded").val());
  var calculatedDate = addDays(startDate, addedDays);
  console.log(addedDays);
  console.log(calculatedDate)
  $("#dayResult").val(calculatedDate.toISOString().split("T")[0]);
});

function addDays(date, days) {
  var result = new Date(date);
  result.setDate(result.getDate() + days);
  return result;
};
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<input type='number' id='daysAdded' class='editField'>
<input type='text' id='dayResult'>

Upvotes: 1

Related Questions