Contents

時間換算的小技巧

在處理時間字串時,「時:分:秒」與秒數的相互換算是常見需求。本文整理 JavaScript 和 PHP 中的時間換算技巧,以及常用的時間單位換算常數。

時:分 字串轉換為秒數

JavaScript 版本

1
2
3
4
5
6
7
8
9
// 將 'HH:MM' 或 'HH:MM:SS' 格式轉換為秒數
function timeToSeconds(time) {
  const parts = time.split(':').reverse();
  return parts.reduce((acc, val, index) => acc + Math.pow(60, index) * Number(val), 0);
}

console.log(timeToSeconds('01:10'));     // 70 秒
console.log(timeToSeconds('01:30:00')); // 5400 秒
console.log(timeToSeconds('00:01:30')); // 90 秒

利用 Math.pow(60, index) 的技巧:從最低位(秒)開始,index 0 乘以 60⁰=1,分鐘乘以 60¹=60,小時乘以 60²=3600。

PHP 版本

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function timeToSeconds($time) {
    $parts = array_reverse(explode(':', $time));
    $seconds = 0;
    foreach ($parts as $index => $value) {
        $seconds += pow(60, $index) * $value;
    }
    return $seconds;
}

echo timeToSeconds('01:10');     // 70
echo timeToSeconds('01:30:00'); // 5400

秒數轉換為時:分:秒

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// 秒數轉為 HH:MM:SS 格式
function secondsToTime(totalSeconds) {
  const hours = Math.floor(totalSeconds / 3600);
  const minutes = Math.floor((totalSeconds % 3600) / 60);
  const seconds = totalSeconds % 60;

  return [hours, minutes, seconds]
    .map(v => String(v).padStart(2, '0'))
    .join(':');
}

console.log(secondsToTime(70));   // "00:01:10"
console.log(secondsToTime(5400)); // "01:30:00"

常用時間換算常數

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
const ONE_SECOND = 1000;          // 1 秒 = 1000 毫秒
const ONE_MINUTE = 60 * 1000;     // 1 分鐘 = 60,000 毫秒
const ONE_HOUR   = 60 * ONE_MINUTE; // 1 小時 = 3,600,000 毫秒
const ONE_DAY    = 24 * ONE_HOUR;   // 1 天 = 86,400,000 毫秒

// 計算兩個時間點的差距
const startTime = new Date('2024-01-01T08:00:00');
const endTime   = new Date('2024-01-01T10:30:00');
const diffMs    = endTime - startTime;

console.log(diffMs / ONE_SECOND); // 9000 秒
console.log(diffMs / ONE_MINUTE); // 150 分鐘
console.log(diffMs / ONE_HOUR);   // 2.5 小時

JavaScript Date 物件基本操作

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
const now = new Date();

// 取得各時間元件
now.getFullYear();    // 年(如 2024)
now.getMonth();       // 月(0-11,注意從 0 開始)
now.getDate();        // 日(1-31)
now.getHours();       // 時(0-23)
now.getMinutes();     // 分(0-59)
now.getSeconds();     // 秒(0-59)
now.getTime();        // 毫秒數(Unix timestamp × 1000)

// 計算 N 天後的日期
const threeDaysLater = new Date(now.getTime() + 3 * ONE_DAY);

使用函式庫(推薦)

複雜的時間操作建議使用成熟的函式庫,避免自行處理各種邊際情況(夏令時、時區轉換等):

Day.js(輕量、API 接近 Moment.js)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// npm install dayjs
import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';
dayjs.extend(duration);

const diff = dayjs('2024-01-01T10:30:00').diff(dayjs('2024-01-01T08:00:00'));
const dur = dayjs.duration(diff);

console.log(dur.hours());   // 2
console.log(dur.minutes()); // 30
console.log(dur.format('HH:mm:ss')); // "02:30:00"

date-fns(Tree-shakable、函式式風格)

1
2
3
4
5
6
7
8
// npm install date-fns
import { differenceInSeconds, differenceInMinutes, format } from 'date-fns';

const start = new Date('2024-01-01T08:00:00');
const end   = new Date('2024-01-01T10:30:00');

console.log(differenceInSeconds(end, start));  // 9000
console.log(differenceInMinutes(end, start));  // 150

參考資料