所以我一直在寻找能够在两个日期之间获得时间跨度的函数,并且我已经在SO上找到了这个答案
Work with a time span in Javascript
但是,日期格式为7/Nov/2012 20:30:00
,日期为7/11/2012 20:30:00
,我的值来自输入
http://jsbin.com/igaruj/47/edit
如果试图改变" Nov"至" 11"我输出了NaN。我必须转换日期吗?
这是代码。
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
</head>
<body>
<input type="text" id ="start"value="7/Nov/2012 20:30:00" />
<input type="text" id="end" value="20/Nov/2012 19:15:00" />
</body>
</html>
javascript
var startDate = document.getElementById("start").value;
var endDate = document.getElementById("end").value;
var date1 = new Date(startDate);
var date2 = new Date(endDate);
var diff = date2.getTime() - date1.getTime();
var days = Math.floor(diff / (1000 * 60 * 60 * 24));
diff -= days * (1000 * 60 * 60 * 24);
var hours = Math.floor(diff / (1000 * 60 * 60));
diff -= hours * (1000 * 60 * 60);
var mins = Math.floor(diff / (1000 * 60));
diff -= mins * (1000 * 60);
var seconds = Math.floor(diff / (1000));
diff -= seconds * (1000);
console.log(days + " days : " + hours + " hours : " + mins + " minutes : " + seconds + " seconds");
答案 0 :(得分:1)
使用您的20/11/2012 20:30:00日期格式:
var startDate = "7/11/2012 20:30:00";
var endDate = "20/11/2012 19:15:00";
您正在获取NaN,因为它需要格式为mm / dd / yyyy。所以20当然是一个无效的月份..交换月份和日期值,如:
var parts = startDate.split('/');
startDate = parts[1] + '/' + parts[0] + '/' + parts[2];
// 11/7/2012 20:30:00
var parts = endDate.split('/');
endDate = parts[1] + '/' + parts[0] + '/' + parts[2];
// 11/20/2012 9:15:00
然后做正常的时间差异工作,它会起作用:
var date1 = new Date(startDate);
var date2 = new Date(endDate);
var diff = date2.getTime() - date1.getTime();
var days = Math.floor(diff / (1000 * 60 * 60 * 24));
diff -= days * (1000 * 60 * 60 * 24);
var hours = Math.floor(diff / (1000 * 60 * 60));
diff -= hours * (1000 * 60 * 60);
var mins = Math.floor(diff / (1000 * 60));
diff -= mins * (1000 * 60);
var seconds = Math.floor(diff / (1000));
diff -= seconds * (1000);
alert(days + " days : " + hours + " hours : " + mins + " minutes : " + seconds + " seconds");
//12 days 22 hours 45 minutes 0 seconds
<强> See the DEMO here 强>
答案 1 :(得分:0)
使用JavaScript Date
并只需调用new Date("7/Nov/2012 20:30:00")
即可获取JS Date对象。然后,您可以使用该Date对象上的方法提取日,月和年。