我需要计算两个日期之间的日差,并且我的代码存在问题。例如,目标日期包含在输入字段(id =“targetdate”)中,格式为 dd / mm / yyyy :
2014年9月2日
我有以下代码:
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))));
我在代码中得到错误的结果:
问题出在哪里?
答案 0 :(得分:3)
构建Date
实例时,“月”值以1月的零开头,因此:
var endDate = new Date(year,month-1,day);
// You need to remove one -------^^
另请注意,您应该解析这些字符串,例如:
var day = parseInt(targetdate.substring(0,2), 10);
var month = parseInt(targetdate.substring(3,5), 10);
var year = parseInt(targetdate.substring(6,10), 10);