5

## JavaScript計算兩個日期之間的時間差

toykid 2012-06-08 11:35:3621630 瀏覽

``````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);
``````

### 1 則留言

0

iT邦高手 1 級 ‧ 2012-06-08 19:05:28

``````&lt;pre class="c" name="code">
&lt;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() + "秒");
&lt;/script>
``````

``````&lt;pre class="c" name="code">
&lt;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() + "秒");
&lt;/script>
``````
toykid iT邦新手 5 級 ‧ 2012-06-11 16:53:11 檢舉