javascript中am / pm格式的两次之间的差异

时间:2014-12-19 07:53:45

标签: javascript

我希望在jquery中以AP / PM的格式找到两次之间的差异。

我测试了很多代码,但无法找到任何解决方案。

我的一个代码在这里。

var timeStart = new Date("01/01/2007 " + "05.00 AM").getHours();
var timeStartmin = new Date("01/01/2007 "  + "05.00 AM").getMinutes();
var timeEnd = new Date("01/01/2007 " + "10.30 PM").getHours();
var timeEndmin = new Date("01/01/2007 " + "10.30 PM").getMinutes();

timeStart     =   timeStart+"."+timeStartmin;
timeEnd     =   timeEnd+"."+timeEndmin;

var hourDiff = timeEnd-timeStart;    
alert(hourDiff);

但它不能正常工作。任何机构都可以给我一个建议。

2 个答案:

答案 0 :(得分:8)

您错误地初始化了日期。这就是你应该这样做的方式:

var timeStart = new Date("01/01/2007 " + "05:00 AM");
var timeEnd = new Date("01/01/2007 " + "10:30 PM");

var diff = (timeEnd - timeStart) / 60000; //dividing by seconds and milliseconds

var minutes = diff % 60;
var hours = (diff - minutes) / 60;

然后,无论你想要什么,都可以使用hoursminutes

答案 1 :(得分:0)

首先Date()将不接受"01/01/2007 " + "05.00 PM"它将在getHours()和其他地方返回NaN。所以你需要传递

var timeStart = new Date("01/01/2007 " + "05:00:00").getHours();

并执行此操作:

var diffhour     =   parseInt(timeEnd)-parseInt(timeStart);
var diffmin     =   parseInt(timeStartmin)-parseInt(timeEndmin);

var Diff = diffhour+":"+diffmin;    
alert(Diff);