有兩個日期,要算這兩個日期之間,相差幾小時、幾分、幾秒
目前想的作法是像下面這樣,如果有更好的解法,請各位大大指教。
var ONE_HOUR = 1000 * 60 * 60; // 1小時的毫秒數
var ONE_MIN = 1000 * 60; // 1分鐘的毫秒數
var ONE_SEC = 1000; // 1秒的毫秒數
var Date_A = new Date(2012,6,8,14,0,0);
var Date_B = new Date(2012,6,9,8,30,30);
var diff = Date_B - Date_A;
var leftHours = Math.floor(diff/ONE_HOUR);
if(leftHours > 0) diff = diff - (leftHours * ONE_HOUR);
var leftMins = Math.floor(diff/ONE_MIN);
if(leftMins >0) diff = diff - (leftMins * ONE_MIN);
var leftSecs = Math.floor(diff/ONE_SEC);
console.log("兩個時間差距為%d小時,%d分,%d秒",leftHours,leftMins,leftSecs);
結果是:兩個時間差距為18小時,30分,30秒
若不考慮超過一天的話...也可以這樣..
<pre class="c" name="code">
<script type="text/javascript">
var Date_A = new Date(2012,6,8,14,0,0);
var Date_B = new Date(2012,6,9,8,30,30);
var Date_C = new Date(Date_B - Date_A);
document.write("兩個時間差距為" + Date_C.getUTCHours() + "小時 " + Date_C.getUTCMinutes() + "分 " + Date_C.getUTCSeconds() + "秒");
</script>
再作個跨天計算修正~呵
<pre class="c" name="code">
<script type="text/javascript">
var Date_A = new Date(2012,6,8,14,0,0);
var Date_B = new Date(2012,6,10,8,30,30);
var Date_C = new Date(Date_B - Date_A);
document.write("兩個時間差距為" + Math.floor(Date_C.getTime() / 3600000) + "小時 " + Date_C.getUTCMinutes() + "分 " + Date_C.getUTCSeconds() + "秒");
</script>
謝謝 jer5173大大的指教~