Guide

ISO 8601 フォーマット ガイド: 日付、時刻、タイムゾーン標準

ISO 8601 とは何ですか?

ISO 8601 は、日付と時刻を明確で明確な形式で表すための国際標準です。国際標準化機構 (ISO) によって発行されたこの標準は、世界中のさまざまな日付形式 (MM/DD/YYYY と DD/MM/YYYY など) によって引き起こされる混乱を排除し、日付と時刻の情報を交換する一貫した方法を提供します。

ISO 8601 形式は、次の理由から API、データベース、Web アプリケーションで広く使用されています。

  • 明確な: 日/月の順序に混乱はありません
  • ソート可能: 辞書順ソートが正しく機能します。
  • 機械可読: コンピュータによる解析が容易
  • 人間可読: 人はまだ理解できます
  • ユニバーサル: すべてのタイムゾーンとロケールで動作します。

ISO 8601 形式を使用する理由?

「03/04/2024」のような日付が表示された場合、それは 3 月 4 日を意味しますか、それとも 4 月 3 日を意味しますか?国が違えばこれの解釈も異なります。 ISO 8601 は、常に明確な年-月-日の形式 2024-04-03 を使用することでこの問題を解決します。

// Ambiguous formats (avoid these)
"03/04/2024"  // Is this March 4 or April 3?
"4-3-24"      // Is this 2024 or 1924?

// ISO 8601 format (recommended)
"2024-04-03"  // Always April 3, 2024
"2024-04-03T14:30:00Z"  // April 3, 2024, 2:30 PM UTC

ISO 8601 の日付形式

基本的な日付形式

標準の ISO 8601 日付形式は、「YYYY-MM-DD」のパターンに従います。

例:

  • 「2024-01-15」 - 2024 年 1 月 15 日
  • 「2024-12-31」 - 2024 年 12 月 31 日
  • 「2025-06-07」 - 2025 年 6 月 7 日
# Python example
from datetime import date

today = date(2024, 4, 15)
iso_date = today.isoformat()  # "2024-04-15"
print(f"ISO 8601 date: {iso_date}")

拡張形式と基本形式

ISO 8601 は 2 つの形式をサポートしています。

  1. 拡張形式 (区切り文字あり): 2024-04-15
  2. 基本形式 (コンパクト): 20240415

ほとんどのアプリケーションは、読みやすい拡張形式を使用します。

// JavaScript example
const date = new Date('2024-04-15');

// Extended format (recommended)
const extended = date.toISOString().split('T')[0];  // "2024-04-15"

// Basic format (compact)
const basic = extended.replace(/-/g, '');  // "20240415"

曜日

ISO 8601 は、「YYYY-Www-D」形式を使用した週ベースの日付もサポートしています。

  • YYYY: 年
  • Www: 週番号 (01-53)
  • D: 曜日 (1=月曜日、7=日曜日)

例: 「2024-W15-3」は、2024 年の第 15 週の水曜日を意味します。

日付の順序

序数の日付 (年間通算日) を使用することもできます: YYYY-DDD

例: 「2024-366」は、2024 年 12 月 31 日を意味します (うるう年なので 366 日)。


ISO 8601 時間形式

基本的な時刻形式

標準の ISO 8601 時刻形式は次のとおりです: HH:MM:SS または HH:MM:SS.sss

例:

  • 「14:30:00」 - 午後 2:30:00
  • 「09:05:30」 - 午前 9:05:30
  • 23:59:59.999 - 午後 11:59:59.999 (ミリ秒)
// Java example
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

LocalTime time = LocalTime.of(14, 30, 0);
String isoTime = time.format(DateTimeFormatter.ISO_LOCAL_TIME);
System.out.println("ISO 8601 time: " + isoTime);  // "14:30:00"

小数秒

ISO 8601 は、さまざまな精度の小数秒をサポートします。

  • 14:30:00.5 - 0.5秒
  • 14:30:00.123 - ミリ秒 (3 桁)
  • 14:30:00.123456 - マイクロ秒 (6 桁)
  • 14:30:00.123456789 - ナノ秒 (9 桁)
// Go example
package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    // ISO 8601 with milliseconds
    iso := now.Format("15:04:05.000")
    fmt.Println("ISO 8601 time:", iso)
}

ISO 8601 日時形式

日付と時刻の組み合わせ

日付と時刻の両方を表すために、ISO 8601 では「T」区切り文字「YYYY-MM-DDTHH:MM:SS」を使用します。

例:

  • 2024-04-15T14:30:00 - 2024 年 4 月 15 日午後 2 時 30 分 (現地時間)
  • 2024-12-31T23:59:59 - 2024 年 12 月 31 日午後 11:59:59
# Ruby example
require 'time'

datetime = Time.new(2024, 4, 15, 14, 30, 0)
iso_datetime = datetime.iso8601  # "2024-04-15T14:30:00+00:00"
puts "ISO 8601 datetime: #{iso_datetime}"

「T」区切り文字

T 文字は日付と時刻を区切ります。標準形式では必須ですが、一部のシステムでは読みやすさのために代わりにスペースを受け入れます。

// PHP example
<?php
$datetime = new DateTime('2024-04-15 14:30:00');
$iso8601 = $datetime->format('c');  // "2024-04-15T14:30:00+00:00"
echo "ISO 8601 datetime: " . $iso8601;
?>

ISO 8601 タイムゾーン指定子

ISO 8601 の最も強力な機能の 1 つは、タイムゾーン情報のサポートです。

UTC 時間 (Z 指定子)

Z 接尾辞は UTC (協定世界時) を示し、「ズールー時間」とも呼ばれます。

  • 2024-04-15T14:30:00Z - 午後 2 時 30 分 UTC

Z は「+00:00」の省略形です。

// JavaScript example
const utcDate = new Date('2024-04-15T14:30:00Z');
console.log(utcDate.toISOString());  // "2024-04-15T14:30:00.000Z"

// Always prefer ISO 8601 with Z for UTC times
const timestamp = Date.now();
const isoString = new Date(timestamp).toISOString();
console.log(isoString);  // "2024-04-15T14:30:00.123Z"

タイムゾーンのオフセット

UTC 以外の時刻の場合は、UTC からのオフセットを指定します: ±HH:MM

例:

  • 2024-04-15T14:30:00+05:30 - インドの午後 2 時 30 分 (UTC+5:30)
  • 2024-04-15T14:30:00-04:00 - 東部夏時間 (UTC-4) の午後 2 時 30 分
  • 2024-04-15T14:30:00+00:00 - Z (UTC) と同じ
# Python example with timezone
from datetime import datetime, timezone, timedelta

# UTC time
utc_time = datetime(2024, 4, 15, 14, 30, 0, tzinfo=timezone.utc)
print(utc_time.isoformat())  # "2024-04-15T14:30:00+00:00"

# Custom timezone (UTC+5:30)
ist = timezone(timedelta(hours=5, minutes=30))
ist_time = datetime(2024, 4, 15, 14, 30, 0, tzinfo=ist)
print(ist_time.isoformat())  # "2024-04-15T14:30:00+05:30"

現地時間 (指定子なし)

タイムゾーンが指定されていない場合、時刻は 現地時間 とみなされます。

  • 2024-04-15T14:30:00 - 現地タイムゾーンの午後 2 時 30 分

警告: API やデータベースでは現地時間を使用しないでください。曖昧さを避けるために、常にタイムゾーンを指定してください。


ISO 8601 期間フォーマット

ISO 8601 では、接頭辞 P (「ピリオド」の意味) を使用した期間の特定の表記法が定義されています。

期間形式: P[n]Y[n]M[n]DT[n]H[n]M[n]S

  • P: 期間指定子 (必須)
  • Y: 年
  • M: 月 (T の前)
  • D: 日
  • T: 時間指定子 (日付と時間の構成要素を区切ります)
  • H: 時間
  • M: 分 (T の後)
  • S: 秒

期間の例

P3Y6M4DT12H30M5S  = 3 years, 6 months, 4 days, 12 hours, 30 minutes, 5 seconds
P1Y               = 1 year
P6M               = 6 months
P7D               = 7 days
PT2H30M           = 2 hours, 30 minutes
PT45S             = 45 seconds
P1DT12H           = 1 day, 12 hours
P0D               = 0 days (zero duration)
// JavaScript example (using date-fns or custom parsing)
function parseISO8601Duration(duration) {
    const regex = /P(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?/;
    const matches = duration.match(regex);

    return {
        years: parseInt(matches[1]) || 0,
        months: parseInt(matches[2]) || 0,
        days: parseInt(matches[3]) || 0,
        hours: parseInt(matches[4]) || 0,
        minutes: parseInt(matches[5]) || 0,
        seconds: parseInt(matches[6]) || 0
    };
}

const duration = parseISO8601Duration("P1DT2H30M");
console.log(duration);  // { years: 0, months: 0, days: 1, hours: 2, minutes: 30, seconds: 0 }

週の期間

W を使用して期間を週単位で表すこともできます。

  • P3W = 3週間 (P21Dに相当)

ISO 8601 時間間隔

ISO 8601 は、時間間隔を表現する 3 つの方法をサポートしています。

1. 開始時間と終了時間

<開始>/<終了>

例: 2024-04-15T09:00:00Z/2024-04-15T17:00:00Z (UTC 午前 9 時から午後 5 時まで)

2. 開始時間と期間

<開始>/P<期間>

例: 2024-04-15T09:00:00Z/PT8H (UTC 午前 9 時、8 時間)

3. 期間と終了時間

P<期間>/<終了>

例: PT8H/2024-04-15T17:00:00Z (UTC 午後 5 時に終了する 8 時間)

# Python example for intervals
from datetime import datetime, timedelta

start = datetime(2024, 4, 15, 9, 0, 0)
end = datetime(2024, 4, 15, 17, 0, 0)

# Calculate duration
duration = end - start
print(f"Duration: {duration}")  # 8:00:00

# ISO 8601 interval
interval = f"{start.isoformat()}/{end.isoformat()}"
print(f"Interval: {interval}")

ISO 8601 と RFC 3339 の比較

RFC 3339 は、インターネットで一般的に使用されている ISO 8601 のプロファイルです。主な違い:

特集ISO8601RFC 3339
フォーマットYYYY-MM-DDTHH:MM:SS±HH:MM同じ
UTCZ または +00:00両方許可
小数秒オプション、任意の精度オプション、任意の精度
区切り文字省略可(基本形式)必須 (拡張形式)
時刻区切り文字T は必須ですT またはスペースを使用できます

例:

  • ISO 8601: 2024-04-15T14:30:00Z または 20240415T143000Z
  • RFC 3339: 2024-04-15T14:30:00Z (拡張形式のみ)

最新の API のほとんどは、ISO 8601 の厳密なサブセットである RFC 3339 を使用します。


開発者向けの ISO 8601 ベスト プラクティス

1. ストレージには常に UTC を使用します

すべてのタイムスタンプを「Z」指定子を使用して UTC に保存します。

// ✅ Good - Store in UTC
const timestamp = new Date().toISOString();  // "2024-04-15T14:30:00.123Z"

// ❌ Bad - Storing local time
const localTime = new Date().toString();  // "Mon Apr 15 2024 14:30:00 GMT+0500"

2. タイムゾーン情報を含める

時間を表示するときは、常にタイムゾーン情報を含めてください。

# ✅ Good - Includes timezone
"2024-04-15T14:30:00+05:30"

# ❌ Bad - Missing timezone
"2024-04-15T14:30:00"

3. 拡張フォーマットを使用する

読みやすさを考慮して、拡張形式 (区切り文字付き) を推奨します。

// ✅ Good - Extended format
"2024-04-15T14:30:00Z"

// ❌ Bad - Basic format (hard to read)
"20240415T143000Z"

4. 精度が重要

ユースケースに応じて適切な精度を使用してください。

// High precision for logging
"2024-04-15T14:30:00.123456789Z"

// Standard precision for most applications
"2024-04-15T14:30:00Z"

// Date only when time doesn't matter
"2024-04-15"

5. ISO 8601 文字列を検証する

解析する前に、ISO 8601 文字列を必ず検証してください。

// JavaScript validation
function isValidISO8601(dateString) {
    const iso8601Regex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;
    if (!iso8601Regex.test(dateString)) return false;

    const date = new Date(dateString);
    return !isNaN(date.getTime());
}

console.log(isValidISO8601("2024-04-15T14:30:00Z"));  // true
console.log(isValidISO8601("2024-04-15 14:30:00"));   // false

避けるべき ISO 8601 のよくある間違い

1. T 区切り文字がありません

// ❌ Wrong
"2024-04-15 14:30:00Z"

// ✅ Correct
"2024-04-15T14:30:00Z"

2. 間違ったタイムゾーン形式

# ❌ Wrong - Missing colon in offset
"2024-04-15T14:30:00+0530"

# ✅ Correct - Colon in offset
"2024-04-15T14:30:00+05:30"

3. 日付形式の混合

// ❌ Wrong - US format
"04/15/2024T14:30:00Z"

// ✅ Correct - ISO 8601
"2024-04-15T14:30:00Z"

4. 先頭のゼロの省略

# ❌ Wrong
"2024-4-5T9:5:0Z"

# ✅ Correct
"2024-04-05T09:05:00Z"

さまざまなプログラミング言語での ISO 8601

JavaScript / TypeScript

// Current time in ISO 8601
const now = new Date().toISOString();
console.log(now);  // "2024-04-15T14:30:00.123Z"

// Parse ISO 8601 string
const date = new Date("2024-04-15T14:30:00Z");

// Custom formatting (using Intl)
const formatter = new Intl.DateTimeFormat('en-US', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    timeZone: 'UTC',
    hour12: false
});

パイソン

from datetime import datetime, timezone

# Current time in ISO 8601
now = datetime.now(timezone.utc).isoformat()
print(now)  # "2024-04-15T14:30:00.123456+00:00"

# Parse ISO 8601 string
dt = datetime.fromisoformat("2024-04-15T14:30:00+00:00")

# Format as ISO 8601
formatted = dt.strftime("%Y-%m-%dT%H:%M:%S%z")

Java

import java.time.Instant;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

// Current time in ISO 8601
String now = Instant.now().toString();
System.out.println(now);  // "2024-04-15T14:30:00.123Z"

// Parse ISO 8601 string
ZonedDateTime dt = ZonedDateTime.parse("2024-04-15T14:30:00Z");

// Format as ISO 8601
String formatted = dt.format(DateTimeFormatter.ISO_INSTANT);

PHP

<?php
// Current time in ISO 8601
$now = date('c');  // "2024-04-15T14:30:00+00:00"

// Parse ISO 8601 string
$dt = new DateTime("2024-04-15T14:30:00Z");

// Format as ISO 8601
echo $dt->format(DateTime::ATOM);  // ISO 8601 format
?>

### 行く

package main

import (
    "fmt"
    "time"
)

func main() {
    // Current time in ISO 8601
    now := time.Now().UTC().Format(time.RFC3339)
    fmt.Println(now)  // "2024-04-15T14:30:00Z"

    // Parse ISO 8601 string
    dt, _ := time.Parse(time.RFC3339, "2024-04-15T14:30:00Z")
    fmt.Println(dt)
}

ルビー

require 'time'

# Current time in ISO 8601
now = Time.now.utc.iso8601
puts now  # "2024-04-15T14:30:00Z"

# Parse ISO 8601 string
dt = Time.iso8601("2024-04-15T14:30:00Z")

# Format as ISO 8601
formatted = dt.strftime("%Y-%m-%dT%H:%M:%S%z")

ISO 8601 を使用するためのツール

オンラインコンバーター

ライブラリとパッケージ

言語図書館説明
JavaScript日付-FNS最新の日付ユーティリティ ライブラリ
JavaScriptdayjsmoment.js に代わる軽量の代替手段
パイソン日時組み込みの標準ライブラリ
パイソン矢印より良い日付と時間
ジャワjava.time最新の Java 日付/時刻 API
PHPカーボン強化された DateTime API
行く時間標準ライブラリ
ルビー時間標準ライブラリ

実際の使用例

1. API レスポンス

{
  "id": "123",
  "created_at": "2024-04-15T14:30:00Z",
  "updated_at": "2024-04-15T15:45:00Z",
  "scheduled_at": "2024-04-20T09:00:00Z"
}

2. データベースストレージ

-- PostgreSQL with timezone
CREATE TABLE events (
    id SERIAL PRIMARY KEY,
    name VARCHAR(255),
    start_time TIMESTAMPTZ NOT NULL,  -- Stores in ISO 8601 with timezone
    end_time TIMESTAMPTZ NOT NULL
);

INSERT INTO events (name, start_time, end_time)
VALUES ('Meeting', '2024-04-15T14:30:00Z', '2024-04-15T15:30:00Z');

3. ログファイル

[2024-04-15T14:30:00.123Z] INFO: Application started
[2024-04-15T14:30:01.456Z] DEBUG: Loading configuration
[2024-04-15T14:30:02.789Z] INFO: Server listening on port 3000

4. 設定ファイル

# config.yml
scheduled_tasks:
  - name: "Daily backup"
    schedule: "2024-04-15T02:00:00Z"
    interval: "P1D"  # ISO 8601 duration: 1 day

  - name: "Weekly report"
    schedule: "2024-04-15T09:00:00Z"
    interval: "P1W"  # ISO 8601 duration: 1 week

よくある質問

ISO 8601 の「T」は何を意味しますか?

T は、日付コンポーネントと時刻コンポーネントの間の区切り文字です。これは「時間」を表し、曖昧さを避けるために ISO 8601 標準で要求されています。

ISO 8601 は RFC 3339 と同じですか?

RFC 3339 は、インターネットでの使用を目的として設計された ISO 8601 のプロファイル (サブセット) です。 RFC 3339 はより厳格で、常に区切り文字を含む拡張形式を必要としますが、ISO 8601 では基本形式と拡張形式の両方が許可されています。

ISO 8601 ではなぜ YYYY-MM-DD 順序を使用するのですか?

この順序 (最大単位から最小単位) により、自然な並べ替えが可能になります。 ISO 8601 の日付をアルファベット順に並べ替えると、自動的に日付順に並べ替えられます。

「T」の代わりにスペースを使用できますか?

一部のシステムでは読みやすくするためにスペースを受け入れますが、ISO 8601 標準では T 区切り文字が必要です。互換性を最大限に高めるには、常に「T」を使用してください。

タイムスタンプの保存にはどのタイムゾーンを使用すればよいですか?

データベースと API では、タイムスタンプを常に UTC (「Z」指定子付き) で保存してください。ユーザーに表示する場合のみ現地時間に変換します。

夏時間はどのように処理すればよいですか?

DST の問題を避けるために、常に UTC で保存してください。現地時間に変換する場合は、DST を自動的に処理する適切なタイムゾーン ライブラリを使用してください。

小数秒の最大精度はどれくらいですか?

ISO 8601 では最大精度が指定されていません。ほとんどのシステムは、ミリ秒 (3 桁)、マイクロ秒 (6 桁)、またはナノ秒 (9 桁) をサポートしています。

秒がゼロの場合、秒を省略できますか?

一部のシステムは「2024-04-15T14:30Z」を受け入れますが、厳密な ISO 8601 形式では「2024-04-15T14:30:00Z」という秒数が必要です。


関連リソース


結論

ISO 8601 は、ソフトウェア システムで日付と時刻を表現するためのゴールドスタンダードです。 ISO 8601 形式に従うことで、タイムスタンプが明確で並べ替え可能であり、世界中のシステムと互換性があることが保証されます。

重要なポイント:

  • UTC 時間には「YYYY-MM-DDTHH:MM:SSZ」を使用します
  • タイムゾーン情報 (Z または ±HH:MM) を含めます。
  • タイムスタンプを UTC で保存し、現地時間で表示します
  • 解析前に ISO 8601 文字列を検証する
  • 読みやすくするために拡張形式 (区切り文字付き) を使用します

ISO 8601 形式を習得することは、日付と時刻を扱う開発者にとって不可欠です。 API の構築、データの保存、ログ ファイルの解析のいずれの場合でも、ISO 8601 は時間表現に対する信頼性の高い標準化されたアプローチを提供します。

今すぐプロジェクトで ISO 8601 の使用を開始し、日付/時刻の曖昧さを永久に排除してください。 🚀