我希望得到am / pm格式的两个时间和日期之间的差异,并获得24小时格式结果。例如:鉴于时间从01/01/2007(mm / dd / yyyy)开始,时间是08:30:20 AM,时间结束时间是01/02/2007,时间是05:30:30,结果是21: 00:10。
var timeStart = new Date("01/01/2007 " + "08:30:20 AM");
var timeEnd = new Date("01/02/2007 " + "05:30:30 PM");
var diff = (timeEnd - timeStart);
var seconds = diff / 6000;
var minutes = (diff - seconds)/ 60;
var hours = (diff - minutes) / 60;
$("#start").text(timeStart);
$("#end").text(timeEnd);
$("#diff").text(diff);
$("#sec").text(seconds);
$("#min").text(minutes);
$("#hr").text(hours);

div{
background-color:yellow;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Time Start: <div id="start"></div><br>
Time End: <div id="end"></div><br>
Difference: <div id="diff"></div><br>
Seconds: <div id="sec"></div><br>
Minutes: <div id="min"></div><br>
Hours: <div id="hr"><div><br>
&#13;
答案 0 :(得分:1)
从此site
var timeStart = new Date("01/01/2007 " + "08:30:20 AM");
var timeEnd = new Date("01/02/2007 " + "05:30:30 PM");
function datediff(fromDate,toDate,interval) {
/*
* DateFormat month/day/year hh:mm:ss
* ex.
* datediff('01/01/2011 12:00:00','01/01/2011 13:30:00','seconds');
*/
var second=1000, minute=second*60, hour=minute*60, day=hour*24, week=day*7;
fromDate = new Date(fromDate);
toDate = new Date(toDate);
var timediff = toDate - fromDate;
if (isNaN(timediff)) return NaN;
switch (interval) {
case "years": return toDate.getFullYear() - fromDate.getFullYear();
case "months": return (
( toDate.getFullYear() * 12 + toDate.getMonth() )
-
( fromDate.getFullYear() * 12 + fromDate.getMonth() )
);
case "weeks" : return Math.floor(timediff / week);
case "days" : return Math.floor(timediff / day);
case "hours" : return Math.floor(timediff / hour);
case "minutes": return Math.floor(timediff / minute);
case "seconds": return Math.floor(timediff / second);
default: return undefined;
}
}
$("#start").text(timeStart);
$("#end").text(timeEnd);
$("#diff").text(timeEnd - timeStart);
$("#sec").text(datediff(timeStart, timeEnd, 'seconds') % 60);
$("#min").text(datediff(timeStart, timeEnd, 'minutes') % 60);
$("#hr").text(datediff(timeStart, timeEnd, 'hours'));
&#13;
div{
background-color:yellow;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Time Start: <div id="start"></div><br>
Time End: <div id="end"></div><br>
Difference: <div id="diff"></div><br>
Seconds: <div id="sec"></div><br>
Minutes: <div id="min"></div><br>
Hours: <div id="hr"><div><br>
&#13;