另一种选择:
// parses the hh:mm:ss out of the div's text
function timeStrToDate(str){
// look for hh:mm:ss and extract it
var m = str.match(/(\d{1,2}:\d{1,2}:\d{1,2})/);
if(m){
// we were able to locate it, so convert it to a Date
// (we only care about time, so use epoc as a ref. point)
return new Date('Thu, 01 Jan 1970 ' + m[1]);
}
// return an empty time by default
return new Date('Thu, 01 Jan 1970');
}
// converts straight seconds in to hh:mm:ss
function secondsToTime(sec){
var r = [], d
// go through by hours, minutes then seconds
// and divide then subtract each time
var exp = [3600,60,1];
for (e = 0; e < exp.length; e++){
if (sec >= exp[e]){
d = Math.floor(sec / exp[e]);
sec -= d * exp[e];
r.push(d < 10 ? '0'+d : d); // pad it so 9 becomes 09
}
}
return r.join(':');
}
// the actual jQuery code
// grab all divs
var $divs = $('div.co,div.cv');
// Grab first element, get text, and parse the time out
var $first = timeStrToDate($divs.first().text()),
// do the same with the last
$last = timeStrToDate($divs.last().text()),
// get the difference (returned in seconds elapsed)
$delta = Math.abs($last - $first) / 1e3; // `/1e3` -> milliseconds to seconds
// here's the end result, 4:59 in this case
console.log(secondsToTime($delta));