Reputation: 509
I need to calculate the day difference between two dates and have the problem with my code. For example, the target date is contained in an input-field (id="targetdate") and has the format dd/mm/yyyy:
09.02.2014
I have the following code:
targetdate = $('#targetdate').val();
// the format is "dd/mm/yyyy", so I need to write the following extra code:
var day = targetdate.substring(0,2);
var month = targetdate.substring(3,5);
var year = targetdate.substring(6,10);
// Calculation difference of days
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var endDate = new Date(year,month,day);
var today = new Date();
var diffDays = (Math.round(Math.abs((endDate.getTime() - today.getTime())/(oneDay))));
I get wrong results with the code:
Where is the problem?
Upvotes: 2
Views: 162
Reputation: 1074495
When constructing a Date
instance, the "months" value starts with zero for January, so:
var endDate = new Date(year,month-1,day);
// You need to remove one -------^^
Also note that you should be parsing those strings, e.g.:
var day = parseInt(targetdate.substring(0,2), 10);
var month = parseInt(targetdate.substring(3,5), 10);
var year = parseInt(targetdate.substring(6,10), 10);
Upvotes: 3