Guide

UTC タイムスタンプの操作 - 完全ガイド

はじめに

UTC (協定世界時) は、コンピューティングおよびネットワークで使用される標準時刻基準です。 UTC タイムスタンプの操作方法を理解することは、複数のタイムゾーンにまたがって動作し、正確な時刻計算が必要なアプリケーションを構築するために不可欠です。

UTC について理解する

UTC 時間とは何ですか?

UTC は次のような標準時間です。

  • タイムゾーン オフセットなし (夏時間なし)
  • 24 時間形式を使用します (00:00:00 ~ 23:59:59.999)
  • ISO 8601 では「Z」として表されます (例: 2025-01-07T12:00:00.000Z)
  • 他のすべてのタイムゾーンの基準として機能します

UTC と現地時間

重要な概念: 現地時間は地理的な場所とタイムゾーンによって異なります。 UTC は世界中で一定です。

特徴UTC 時間現地時間
タイムゾーン オフセット常に UTC+00:00場所によって異なります (例: UTC-5、UTC+8、UTC-10)
夏時間DST 調整なし季節や地域によって異なります
一貫性世界的に一貫性のあるシステムが異なれば現地時間も異なる場合があります。
主な使用例グローバル システム、データベース、APIユーザー向けアプリケーション、カレンダー イベント
ストレージサイズ他のタイムスタンプと同じ (追加のオーバーヘッドなし)DateTime と同じ (より大きなストレージ)
クエリのパフォーマンス優れた (数値比較)遅い (日時解析が必要)

警告: 常に UTC タイムスタンプをデータベースに保存してください。表示目的のみで現地時間に変換します。

UTC タイムスタンプ形式

ISO 8601

ISO 8601 の UTC タイムスタンプは常に「Z」で終わります。

2025-01-07T12:00:00.000Z  // January 7, 2025, 12:00:00 UTC

Unix タイムスタンプ

UTC タイムスタンプは、Unix エポック (1970-01-01 00:00:00 UTC) からの秒数です。

1735689600 // January 1, 2025, 00:00:00 UTC

UTC から現地時間への変換

JavaScript

// Convert UTC timestamp (seconds) to local time
function utcToLocal(utcTimestampSeconds, timezoneOffsetHours = 0) {
  const date = new Date(
    (utcTimestampSeconds * 1000) + (timezoneOffsetHours * 60 * 60 * 1000),
  );
  return date.toLocaleString(); // Returns string like "1/7/2025, 6:12:00 PM"
}

// Get UTC timestamp and convert to local
const now = Math.floor(Date.now() / 1000);
console.log(utcToLocal(now, -5)); // UTC-5 for EST

パイソン

from datetime import datetime, timezone
from zoneinfo import ZoneInfo

# Convert UTC to specific timezone
def utc_to_local(utc_timestamp: int, timezone_str: str) -> datetime:
    """
    Convert UTC timestamp to local datetime in specified timezone.

    Args:
        utc_timestamp: Unix timestamp in seconds
        timezone_str: IANA timezone name (e.g., 'America/New_York')

    Returns:
        Local datetime object
    """
    utc_time = datetime.fromtimestamp(utc_timestamp, tz=timezone.utc)
    return utc_time.astimezone(ZoneInfo(timezone_str))

# Example
print(utc_to_local(1735689600, "America/Los_Angeles"))

SQL

-- MySQL: Convert UTC timestamp to datetime
-- Note: Use FROM_UNIXTIME() which respects the system timezone setting

-- Convert UTC timestamp to MySQL DATETIME
SELECT
  id,
  FROM_UNIXTIME(created_at) AS mysql_datetime,
  created_at
FROM events
WHERE id = ?;

-- Store current UTC timestamp
UPDATE events
SET created_at = UNIX_TIMESTAMP(NOW());

-- PostgreSQL: Use TIMESTAMPTZ for timezone-aware storage
CREATE TABLE events (
  id BIGSERIAL PRIMARY KEY,
  event_timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  event_date TIMESTAMP WITH TIME ZONE 'UTC'
);

-- Query events with local time display
SELECT
  id,
  event_timestamp,
  TO_CHAR(event_timestamp, 'YYYY-MM-DD HH24:MI:SS') AS local_time
FROM events;

ベスト プラクティス: 常に UTC タイムスタンプを保存します。アプリケーションレベルのタイムゾーン変換は表示のみに使用します。

タイムゾーンの処理

タイムゾーン オフセットについて

タイムゾーン オフセットは次のように表されます。

  • UTC+XX:00 (例: UTC-5:00)
  • UTC-XX:00 (例: UTC+8:00)
オフセット営業時間都市地域
UTC-5:00-5ニューヨーク、トロント、ボゴタ、リマ東部標準時
UTC-8:00-8ロサンゼルス、サンフランシスコ、ティファナ太平洋標準時
UTC+0:000ロンドン、ダブリン、リスボン西ヨーロッパ時間
UTC+1:00+1パリ、ベルリン、ローマ中央ヨーロッパ時間
UTC+8:00+8シンガポール、香港、パース中国標準時
UTC+9:00+9東京、ソウル、平壌日本標準時
UTC+10:00+10シドニー、メルボルン、ブリスベンオーストラリア東部標準時
UTC+12:00+12オークランドニュージーランド標準時

タイムゾーン変換の例

JavaScript のタイムゾーン変換

// Convert between UTC and different timezones
function convertToTimezone(utcDate, timezone) {
  const options = { timeZone: timezone };
  return utcDate.toLocaleString('en-US', options);
}

// Examples
const utcDate = new Date('2025-01-07T12:00:00.000Z');

console.log(convertToTimezone(utcDate, 'America/New_York'));    // "1/7/2025, 7:00:00 AM EST"
console.log(convertToTimezone(utcDate, 'Asia/Tokyo'));      // "2025/1/7, 21:00:00 JST"
console.log(convertToTimeDate, 'Europe/London'));     // "1/7/2025, 12:00:00 GMT"
console.log(convertToTimezone(utcDate, 'Asia/Shanghai'));   // "2025/1/7, 20:00:00 CST"
// Python timezone handling
from datetime import datetime, timezone

# Get current UTC time and convert to timezone
now_utc = datetime.now(timezone.utc)

# Convert to specific timezone
now_tokyo = now_utc.astimezone('Asia/Tokyo')
now_est = now_utc.astimezone('America/New_York')
now_gmt = now_utc.astimezone('Etc/GMT')

print(f"UTC: {now_utc}")
print(f"Tokyo: {now_tokyo}")
print(f"EST: {now_est}")
print(f"GMT: {now_gmt}")

ベストプラクティス

UTC ストレージのガイドライン

ストレージ: 常に UTC タイムスタンプを保存します。これらはタイムゾーンに依存せず、グローバルなアプリケーションにとって効率的です。

表示: UI レイヤーでのみローカル タイムゾーンに変換します。現地時間をデータベースに保存しないでください。

クエリ: 常に UTC タイムスタンプでフィルタリングおよび並べ替えます。これにより、ユーザーのタイムゾーンに関係なく、一貫した順序が確保されます。

API: API 応答では常に UTC タイムスタンプを使用します。 API ドキュメントにタイムゾーンを記載します。

重要な警告: 同じ列内で UTC タイムスタンプとローカル タイムスタンプを決して混在させないでください。これにより、データの整合性の問題やクエリの不一致が発生します。

よくある落とし穴

落とし穴 1: タイムゾーンを忘れる

問題: すべての場所で同時に DST が適用されるわけではありません。

例: アリゾナ州は夏時間を遵守していませんが、ニューヨーク州は夏時間を遵守しています。これにより、特定の期間においてそれらの間に 1 時間の差異が生じる可能性があります。

解決策: 過去および現在の DST ルールを含む IANA タイムゾーン データベース (tz データベース) を使用します。

落とし穴 2: タイムゾーン オフセットが正しくない

問題: タイムゾーン名の代わりにハードコーディングされたオフセットを使用しています。

Bad: const offset = -5 * 3600000; // EST は常に -5 ですが、アリゾナは DST を遵守しません

良い: const offset = 'America/New_York'; // 正しい過去の DST を持つ IANA データベースを使用します

落とし穴 3: すべての時刻が同じ形式であると仮定する

問題: すべてのシステムが UTC を使用するわけではありません (例: GMT を使用するシステムもあれば、UTC+X を使用するシステムもあります)。

例: Unix タイムスタンプは常に UTC ベースですが、ファイル システムは異なる場合があります。

解決策: ユーザー入力を解析するときは、常にタイムゾーンを明示的に指定してください。

異なるタイムゾーンでの作業

JavaScript

// Best practice: Always specify timezone when creating dates
const date1 = new Date('2025-01-07T12:00:00'); // UTC time (good)

const date2 = new Date('2025-01-07T12:00:00-08:00'); // Bad: assumes local timezone

// Convert between timezones
function convertTimezones(fromDate, fromTz, toTz) {
  return {
    fromTime: fromDate.toLocaleString('en-US', { timeZone: fromTz }),
    toTime: fromDate.toLocaleString('en-US', { timeZone: toTz }),
    fromTimestamp: fromDate.getTime(),
    toTimestamp: fromDate.toLocaleString('en-US', { timeZone: toTz }),
  };
}

// Example: Convert UTC to multiple timezones
const utcDate = new Date('2025-01-07T12:00:00.000Z');
const conversions = [
  convertTimezones(utcDate, 'UTC', 'America/New_York'),
  convertTimezones(utcDate, 'UTC', 'Asia/Tokyo'),
  convertTimezones(utcDate, 'UTC', 'Europe/London'),
];

パイソン

from datetime import datetime, timezone

# Best practice: Use pytz library
import pytz

def convert_to_timezone(utc_time: datetime, timezone: str) -> datetime:
    """
    Convert UTC datetime to specified timezone using IANA timezone database.

    Args:
        utc_time: UTC datetime object
        timezone_str: IANA timezone name

    Returns:
        Localized datetime object
    """
    utc_time = utc_time.replace(tzinfo=timezone.tzinfo(utc_time))
    return utc_time.astimezone(timezone)

# Example: Convert current UTC to multiple timezones
now_utc = datetime.now(timezone.utc)
now_est = now_utc.astimezone('America/New_York')
now_gmt = now_utc.astimezone('Etc/GMT')
now_tokyo = now_utc.astimezone('Asia/Tokyo')

print(f"UTC: {now_utc}")
print(f"EST: {now_est}")
print(f"GMT: {now_gmt}")
print(f"JST: {now_tokyo}")

タイムゾーンのベスト プラクティス

タイムゾーン選択ガイドライン

<オル>

<li>常に IANA タイムゾーン名を使用してください(例: 「America/New_York」、「Europe/London」)</li> <li>ハードコードされたオフセットの代わりにタイムゾーン データベース (IANA tz データベース、tz データベース) を使用する</li> <li>対象地域(特に春と秋)で DST 移行をテストする</li> <li>タイムゾーンの想定を API ドキュメントに明確に文書化する</li> <li>すべての内部ストレージと計算に UTC を使用することを検討する</li> <li>タイムゾーン名と現地時間を UI に個別に表示します (UTC を内部的に保存します)</li> </ol>

ツールとリファレンス

関連ツール

概要

重要なポイント: 常に UTC タイムスタンプを保存してください。アプリケーション層またはクエリ層でタイムゾーン変換を処理します。これにより、データの一貫性が確保され、アプリケーションのグローバルな互換性が確保されます。

重要: データベース ストレージ内で UTC タイムスタンプとローカル タイムスタンプを決して混在させないでください。常に UTC を保存し、必要な場合にのみローカルに変換します。

パフォーマンスのヒント: UTC タイムスタンプは次の場合に最適です。

  • データベースのインデックス作成 (数値比較)
  • 範囲クエリ (数値フィルター)
  • ソート操作(数値順)
  • 時間ベースのパーティショニング

コード例リポジトリ

タイムスタンプとタイムゾーンのコード例の詳細については、特定の使用例を扱うための関連ツールとガイドを参照してください。