為何需要在程式碼裡把日期轉 Epoch
大多數應用以 Unix 整數存放時間戳,但收到的日期是字串 — 表單裡的日曆值、CSV 的日期欄、依特定時區格式化的 webhook 欄位。把這些字串在程式碼裡轉成 epoch,資料庫才能排序、服務才能比較、API 才能接受。本文按 JavaScript、Python、SQL、Go、shell 分別給出地道寫法,以及每個團隊遲早都會踩的時區 bug。
JavaScript:Date、getTime 與帶時區的輸入
JavaScript 內部以毫秒儲存時間。Date.UTC 接受 UTC 牆上時間並返回毫秒 epoch;帶顯式偏移量的 ISO 8601 字串可用 new Date(iso).getTime();除以 1000 取得秒。
- Date.UTC(2026, 0, 1, 0, 0, 0) → 1767225600000 (month is zero-indexed)
- new Date('2026-01-01T08:00:00-05:00').getTime() → 1767265200000
- Math.floor(Date.now() / 1000) → current Unix seconds
- Wall-clock in a non-UTC zone needs a zone-aware library (Luxon, date-fns-tz, Temporal)
Python:datetime.timestamp 與 calendar.timegm
Python 的 datetime 物件以 .timestamp() 轉 epoch — 但前提是必須 timezone-aware。naive datetime 會被當作本機本地時間解讀,這是線上 epoch 出錯最常見的原因。
- datetime(2026, 1, 1, tzinfo=timezone.utc).timestamp() → 1767225600.0
- calendar.timegm(struct_time) → seconds (UTC-only)
- datetime.now(ZoneInfo('America/New_York')).timestamp() → zone-aware now
- Avoid datetime.fromisoformat(s).timestamp() when s has no offset
SQL:EXTRACT EPOCH、UNIX_TIMESTAMP、UNIX_SECONDS
每個主流資料庫都提供把時間戳欄位轉 epoch 整數的函式。請明確處理欄位時區:TIMESTAMP WITH TIME ZONE 與 TIMESTAMP WITHOUT TIME ZONE 傳入這些函式的行為差別很大。
- PostgreSQL: EXTRACT(EPOCH FROM ts) → seconds (double)
- MySQL: UNIX_TIMESTAMP(ts) → seconds, naive ts read in session timezone
- BigQuery: UNIX_SECONDS(ts) / UNIX_MILLIS(ts) — TIMESTAMP only
- SQLite: strftime('%s', ts) → seconds as string, cast to integer
Go 與 shell:time.Unix 與 date +%s
Go 用含偏移量的 layout 解析,再呼叫 .Unix() 取秒、.UnixMilli() 取毫秒。shell 端 GNU date -d 能解析常見日期串,BSD / macOS 的 date -j -f 必須明確指定格式。
- Go: t, _ := time.Parse(time.RFC3339, "2026-01-01T00:00:00Z"); t.Unix()
- Go: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC).Unix()
- GNU date: date -d "2026-01-01 00:00:00 UTC" +%s
- macOS date: date -j -u -f "%Y-%m-%d %H:%M:%S" "2026-01-01 00:00:00" +%s
FAQ
- How do I convert time to epoch time?
- Choose the date, clock time, and timezone, then convert that instant to Unix seconds or milliseconds. If the timezone is missing, the result may be off by hours.
- Is timestamp to epoch the same as date to epoch?
- Usually yes. It means converting a readable timestamp or date-time string into an epoch number.
- Should I send epoch seconds or milliseconds to an API?
- Follow the API documentation. If it says Unix timestamp, it often means seconds, but JavaScript-oriented APIs may expect milliseconds.
- Why does the same date give a different epoch in different timezones?
- Because a local wall-clock time only identifies an instant once a timezone is attached. 2026-01-01 00:00 is 1767225600 in UTC but 1767243600 in New York — five hours later in real time. Set the timezone before converting.