JS计算时间差

<script>
function toDouble(str)
{
    return parseInt(str) < 10 ? '0' + str : str;
}

function dateDiff(date1, date2)
{
  var objInterval = {'D': 1000*60*60*24, 'H': 1000*60*60, 'M': 1000*60, 'S': 1000, 'T': 1};
  var dt1 = !isNaN(date1) ? date1 : new Date(Date.parse(date1.replace(/-/g, '/'))).getTime();
  if (date2) var dt2 = !isNaN(date2) ? date2 : new Date(Date.parse(date2.replace(/-/g, '/'))).getTime();
    var diff = date2 ? Math.abs(dt2 - dt1) : dt1;
 
    var result = {};
    
    for(var i in objInterval)
    {
        result[i] = toDouble(Math.round(diff / objInterval[i]));
    }
    
    return result;
}

function countDate(json)
{
    var times = json.T;
    var days = Math.floor(times/(24*3600*1000));
    var remain1 = times%(24*3600*1000);
    var hours = Math.floor(remain1/(3600*1000));
    var remain2 = remain1%(3600*1000);
    var minutes = Math.floor(remain2/(60*1000));
    var remain3 = remain2%(60*1000);
    var seconds = Math.round(remain3/1000);
    
    return {D: days, H: hours, M: minutes, S: seconds}
}

//alert(dateDiff('2007-5-1', '2007/05/19').D);
//alert(dateDiff(1350366321578, 1350366321518).T);

var dt1 = 1349955233000;
var dt2 = 1350148036000;

var diff = countDate(dateDiff(Math.abs(dt1 - dt2)));
alert(diff.D + '天' + diff.H + '小时' + diff.M + '分钟' + diff.S + '秒');
</script>

你可能感兴趣的:(js)