Phoenix Phoenix - 2 days ago 5
Javascript Question

Html5 Date control issue: Adding 3 days to a particular date in December returns the next month January in js

I have a date object which I am setting based on the value selected by the user, from the drop down calendar.I want to add 3 days to the selected one. Its working perfectly fine for all months, except December. If I select a particular date from December and add 3 days, the month value returned is "00" instead of "12".

Here is my code.

var dateinput= document.getElementById("date_picker").value;
console.log(dateinput);
var timeinput= document.getElementById("time_picker").value;
var dateobj = dateinput + ' ' +timeinput;
var parts = dateobj.split(/[-\s:]/);
var date = new Date(parts[0],parts[1],parts[2],parts[3],parts[4]);
console.log(parts[1])
date.setDate( date.getDate() + 3);
console.log(date)


var dateobj2 = [date.getMonth(), date.getDate(), date.getFullYear()].map(pad).join('/') +
' ' + [date.getHours(),date.getMinutes()].map(pad).join(':');

Answer

Basically months will start from 00 (Jan) to 11 (Dec). So when user enters 12 for December, it should be subtracted by 1 to get 11 when you assign the components to new Date(year, month, day, hours, minutes, seconds, milliseconds).

So your code will become,

var date  = new Date(parts[0], parts[1]-1, parts[2], parts[3], parts[4]);

You can check the below snippet,

function getDate() {

      var dateinput= document.getElementById("date_picker").value;
      var timeinput= document.getElementById("time_picker").value;
      var dateobj = dateinput + ' ' +timeinput;
      var parts = dateobj.split(/[-\s:]/);
      var date  = new Date(parts[0], parts[1]-1, parts[2], parts[3], parts[4]);
      date.setDate( date.getDate() + 3);
      console.log(date);
}
<input type="date" id="date_picker" />
<input type="text" id="time_picker" />
<input type="button" value="Get Date" onclick="getDate()" />
<br/>

Comments