我发现了一个类似的问题here但这对我的情况不起作用,因为我的日期是特定格式“yyyy-MM-dd”,即“2014-08-29”和“2014-08- 31" 。
我在下面尝试但没有按预期工作。 “dtpEffectiveFrom”& “dtpEffectiveTo”都是HTML5 日期字段。对于上述日期范围,输出显示的是NaN天而不是3天。
var effectiveFrom = $("#dtpEffectiveFrom").val();
var effectiveTo = $("#dtpEffectiveTo").val();
function daydiff(first, second) {
return (second - first) / (1000 * 60 * 60 * 24);
}
var msg = "Are you applying for a " + daydiff(effectiveFrom, effectiveTo) + " day(s) leave?";
alert(msg);
答案 0 :(得分:2)
看到这段代码。您需要将字符串转换为日期并使用getTime函数以毫秒为单位获取日期。
var effectiveFrom = "2014-08-29";
var effectiveTo = "2014-09-31";
function daydiff(first, second) {
return (second.getTime() - first.getTime()) / (1000 * 60 * 60 * 24) + 1;
}
var days = daydiff(new Date(effectiveFrom), new Date(effectiveTo));
console.log(days);
答案 1 :(得分:1)
尝试使用像这样的daydiff函数:
function daydiff(first, second) {
first=new Date(first);
second=new Date(second);
return (second - first) / (1000 * 60 * 60 * 24);
}
答案 2 :(得分:0)
使用Date对象处理格式...
var effectiveFrom = new Date($("#dtpEffectiveFrom").val());
var effectiveTo = new Date($("#dtpEffectiveTo").val());
function daydiff(first, second) {
return (second - first) / (1000 * 60 * 60 * 24);
}
var msg = "Are you applying for a " + daydiff(effectiveFrom, effectiveTo) + " day(s) leave?";
alert(msg);