javaScriptは二つの文字列の時間差を計算します(XX日XX時XX分XX秒)
2558 ワード
プロジェクトの中で今日は2つの文字列の時間差を計算します.今日は私の解決方法を記録します.
function getDiffTime(startTime,endTime){
var startTimeDate,endTimeDate;
if(startTime){
startTimeDate = new Date(startTime.replace(/-/g, '/')).getTime();
}else{
startTimeDate = new Date().getTime();
}
if(endTime){
endTimeDate = new Date(endTime.replace(/-/g, '/')).getTime();
}else{
endTimeDate = new Date().getTime();
}
var diffTime = endTimeDate - startTimeDate;
var day = diffTime > 0 ? Math.floor(diffTime/1000/60/60/24) : Math.ceil(diffTime/1000/60/60/24);
var hDistance = diffTime - day * 86400*1000;
var hour = hDistance > 0 ? Math.floor(hDistance/3600/1000) : Math.ceil(hDistance/3600/1000);
var mDistance = hDistance - hour * 3600*1000;
var minute = mDistance > 0 ? Math.floor(mDistance/60/1000) : Math.ceil(mDistance/60/1000);
var sDistance = mDistance - minute * 60*1000;
var second = sDistance > 0 ? Math.floor(sDistance/1000) : Math.ceil(sDistance/1000);
return day + ' ' + hour + ' ' + minute+ ' ' + second+ ' ';
}