Guide

RFC 3339 と ISO 8601: 違いは何ですか?

はじめに

ソフトウェア開発でタイムスタンプを扱う場合、RFC 3339ISO 8601 という 2 つの主要な標準に遭遇することになります。これらは関連していますが、異なる目的を果たし、重要な違いがあります。このガイドでは主な違いについて説明し、ニーズに合った適切な形式を選択するのに役立ちます。

概要

側面RFC 3339ISO8601
フルネームRFC 3339: インターネット上の日付と時刻ISO 8601: データ要素と交換形式
目的インターネット プロトコルと Web API一般的なデータ交換
柔軟性厳密で制限された形式オプション柔軟な複数のバリエーション
タイムゾーン必須 (オフセットまたは Z)オプション
小数秒1 秒未満の精度には必須オプション
2024-01-15T12:30:45.123Z2024-01-15T12:30:45 または 2024-01-15T12:30:45.123+05:30
標準ボディIETFISO

主な違い

1. 形式の厳密さ

RFC 3339 はより厳密です - 厳密に 1 つの形式を定義しています。

YYYY-MM-DDThh:mm:ss[.s]TZD

場所:

  • YYYY-MM-DD = 日付
  • T = 時間区切り文字 (リテラル)
  • hh:mm:ss = 時間
  • [.s] = オプションの小数秒
  • TZD = 必須のタイムゾーン指定子 (Z または +/-HH:MM)

ISO 8601 は柔軟性があります - 複数の形式が可能です。

// All valid ISO 8601 formats
2024-01-15                    // Date only
20240115                      // Basic format (no separators)
2024-01-15T12:30:45           // Without timezone
2024-01-15T12:30:45Z          // With Z (UTC)
2024-01-15T12:30:45+05:30     // With offset
2024-01-15T12:30:45.123456    // With microseconds
20240115T123045               // Basic format with time

2. タイムゾーンの要件

RFC 3339 にはタイムゾーンが必要です:

// Valid RFC 3339 timestamps
2024-01-15T12:30:45Z          // UTC (Z)
2024-01-15T12:30:45+05:30     // With offset
2024-01-15T12:30:45-08:00     // With offset

// Invalid RFC 3339 - missing timezone
2024-01-15T12:30:45           // ❌ Not RFC 3339

ISO 8601 ではタイムゾーンがオプションになります:

// Valid ISO 8601 timestamps
2024-01-15T12:30:45Z          // With timezone
2024-01-15T12:30:45+05:30     // With offset
2024-01-15T12:30:45           // Without timezone ✅

3. 小数秒

RFC 3339 では小数点以下の秒が許可されていますが、必須ではありません:

// Both valid RFC 3339
2024-01-15T12:30:45Z          // Whole seconds
2024-01-15T12:30:45.123Z      // With milliseconds
2024-01-15T12:30:45.123456Z    // With microseconds

ISO 8601 では秒の小数点以下も許可されます:

// All valid ISO 8601
2024-01-15T12:30:45Z
2024-01-15T12:30:45.123Z
2024-01-15T12:30:45.123456Z
2024-01-15T12:30:45.123456789Z // Nanoseconds

4. 区切り文字

RFC 3339 ではハイフンとコロンが必要です:

// Valid RFC 3339
2024-01-15T12:30:45Z

// Invalid RFC 3339
20240115T123045Z      // ❌ Basic format
2024/01/15T12:30:45Z  // ❌ Wrong separators

ISO 8601 では基本的な形式が許可されています (区切り文字なし):

// Both valid ISO 8601
2024-01-15T12:30:45Z    // Extended format
20240115T123045Z        // Basic format ✅

どの形式を使用する必要がありますか?

RFC 3339 は次の目的で使用します。

  1. Web API - JSON 応答、HTTP ヘッダー
  2. ネットワーク プロトコル - 電子メール、HTTP、WebSocket
  3. 認証トークン - JWT、OAuth タイムスタンプ
  4. クラウド サービス - AWS、Google Cloud API の応答
  5. OpenAPI 仕様 - API ドキュメント

例: Web API レスポンス

{
  "user_id": "12345",
  "created_at": "2024-01-15T12:30:45.123Z",
  "updated_at": "2024-01-15T14:20:30.456Z",
  "expires_at": "2024-02-15T12:30:45.123Z"
}

ISO 8601 は次の目的で使用します。

  1. データベース ストレージ - DATETIME 列
  2. ファイルの命名 - ログ、バックアップ
  3. データ ファイル - CSV、JSON、XML
  4. ユーザー インターフェイス - 表示の柔軟性
  5. 設定ファイル - タイムゾーンがコンテキストに依存する場合

例: データベース レコード

-- ISO 8601 in database
INSERT INTO events (id, timestamp, description)
VALUES (1, '2024-01-15T12:30:45', 'Event occurred');

例: ファイルの命名

# ISO 8601 basic format (no timezone needed for local files)
backup-20240115-123045.sql.gz
log-20240115-123045.txt

コード例

JavaScript

RFC 3339 の解析

// Both RFC 3339 and ISO 8601 parse correctly
const timestamp1 = new Date('2024-01-15T12:30:45.123Z');
console.log(timestamp1.toISOString()); // "2024-01-15T12:30:45.123Z"

const timestamp2 = new Date('2024-01-15T12:30:45+05:30');
console.log(timestamp2.toISOString()); // "2024-01-15T07:00:45.000Z"

RFC 3339 の生成

function toRFC3339(date) {
  // JavaScript's toISOString() returns RFC 3339-compatible format
  return date.toISOString();
}

console.log(toRFC3339(new Date()));
// "2024-01-15T12:30:45.123Z"

パイソン

RFC 3339 の解析

from datetime import datetime

# Both RFC 3339 and ISO 8601 work with datetime
timestamp1 = datetime.fromisoformat('2024-01-15T12:30:45.123')
print(timestamp1.isoformat())

# For parsing with timezone
from dateutil import parser

timestamp2 = parser.parse('2024-01-15T12:30:45.123+05:30')
print(timestamp2)

RFC 3339 の生成

from datetime import datetime, timezone

def to_rfc3339(dt):
    """Convert datetime to RFC 3339 format."""
    if dt.tzinfo is None:
        # Assume UTC if no timezone
        dt = dt.replace(tzinfo=timezone.utc)
    return dt.strftime('%Y-%m-%dT%H:%M:%S.%f%z').replace('+00:00', 'Z')

now = datetime.now(timezone.utc)
print(to_rfc3339(now))
# "2024-01-15T12:30:45.123456Z"

Java

RFC 3339 の解析

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

// RFC 3339 formatter
DateTimeFormatter rfc3339 = DateTimeFormatter.ISO_INSTANT;

// Parse RFC 3339 timestamp
Instant instant = Instant.parse("2024-01-15T12:30:45.123Z");
System.out.println(instant); // 2024-01-15T12:30:45.123Z

// Format to RFC 3339
String formatted = instant.format(rfc3339);
System.out.println(formatted); // 2024-01-15T12:30:45.123Z

一般的な使用例

1. RESTful API

ベスト プラクティス: RFC 3339 を使用します

// API Response
app.get('/api/users/:id', (req, res) => {
  const user = getUser(req.params.id);

  res.json({
    id: user.id,
    name: user.name,
    created_at: user.createdAt.toISOString(), // RFC 3339
    updated_at: user.updatedAt.toISOString()  // RFC 3339
  });
});

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

ベスト プラクティス: ISO 8601 (またはネイティブ DATETIME) を使用します

-- MySQL
CREATE TABLE events (
  id INT PRIMARY KEY,
  event_time DATETIME(3),  -- Millisecond precision
  description VARCHAR(255)
);

-- ISO 8601 format for INSERT
INSERT INTO events VALUES (1, '2024-01-15 12:30:45.123', 'Event');

3. ログファイル

ベスト プラクティス: ISO 8601 をタイムゾーンとともに使用する

# Nginx log format example
2024-01-15T12:30:45.123+00:00 [INFO] Request received
2024-01-15T12:30:45.456+00:00 [INFO] Processing complete

4. 認証

ベスト プラクティス: RFC 3339 を使用します

// JWT token with RFC 3339 timestamps
const token = {
  sub: 'user123',
  iat: Math.floor(Date.now() / 1000),           // Issued at
  exp: Math.floor(Date.now() / 1000) + 3600     // Expires in 1 hour
};

互換性ガイド

RFC 3339 をサポートするライブラリ

言語図書館メモ
JavaScriptDate.toISOString()内蔵
JavaScriptmoment.jsRFC 3339 を完全にサポート
JavaScriptルクソンRFC 3339 を完全にサポート
パイソン日時部分的 (dateutil を使用)
パイソン矢印RFC 3339 を完全にサポート
ジャワjava.timeInstantZonedDateTime
行く時間RFC3339 形式定数
ルビーTime.iso8601両方をサポート

ブラウザのサポート

// All modern browsers support RFC 3339 parsing
const date1 = new Date('2024-01-15T12:30:45.123Z');
const date2 = new Date('2024-01-15T12:30:45+05:30');

// IE 11 and older may have issues with fractional seconds
// Polyfill recommended for legacy browsers

よくある間違い

1. フォーマットの混合

// ❌ Bad: Mixing formats in same API
{
  "created_at": "2024-01-15T12:30:45Z",      // RFC 3339
  "updated_at": "2024-01-15 12:30:45",      // SQL format
  "expires_at": 1705313445000                  // Unix timestamp
}

// ✅ Good: Consistent RFC 3339 format
{
  "created_at": "2024-01-15T12:30:45.000Z",
  "updated_at": "2024-01-15T12:35:30.456Z",
  "expires_at": "2024-02-15T12:30:45.123Z"
}

2. タイムゾーンを忘れる

// ❌ Bad: Missing timezone (ambiguous)
const timestamp = '2024-01-15T12:30:45';

// ✅ Good: Include timezone
const timestamp = '2024-01-15T12:30:45Z';      // UTC
const timestamp = '2024-01-15T12:30:45+05:30'; // Local

3. 非標準フォーマットの使用

// ❌ Bad: Custom format
const timestamp = '01/15/2024 12:30:45 PM';

// ✅ Good: RFC 3339
const timestamp = '2024-01-15T12:30:45Z';

比較表

特集RFC 3339ISO8601勝者
Web API✓ 優先RFC 3339
ネットワーク プロトコル✓ 必須-RFC 3339
データベース ストレージネクタイ
ファイル名✓ 優先ISO8601
柔軟性-ISO8601
厳格さ-RFC 3339
タイムゾーンは必須です-RFC 3339
ブラウザのサポートネクタイ

よくある質問

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

A: RFC 3339 は ISO 8601 のサブセットです。RFC 3339 は、特にインターネット プロトコルでの使用を目的とした ISO 8601 の厳密なプロファイルを定義します。すべての RFC 3339 タイムスタンプは ISO 8601 で有効ですが、すべての ISO 8601 タイムスタンプが RFC 3339 で有効であるわけではありません。

Q: API にはどの形式を使用すればよいですか?

A: RFC 3339 を使用します。これは Web API の標準であり、タイムゾーン情報が存在することを保証し、すべてのプログラミング言語とフレームワークで広くサポートされています。

Q: タイムスタンプを ISO 8601 としてデータベースに保存できますか?

A: はい、ただし、ほとんどのデータベースにはネイティブの日時型があります。文字列として保存する代わりに、データベースの DATETIME または TIMESTAMP 列タイプを使用します。データをエクスポート/インポートする必要がある場合は、ISO 8601 文字列表現を使用してください。

Q: RFC 3339 形式を検証するにはどうすればよいですか?

A: 正規表現またはライブラリ検証を使用します。

// Regex for RFC 3339
const rfc3339Regex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;

if (!rfc3339Regex.test(timestamp)) {
  throw new Error('Invalid RFC 3339 format');
}

Q: Unix のタイムスタンプについてはどうですか?

A: Unix タイムスタンプ (ミリ秒またはエポックからの秒数) も、特に次のような多くのユースケースで有効です。

  • 内部計算
  • 高性能アプリケーション
  • 時間の比較

ただし、次の場合には RFC 3339 の方が適しています。

  • API 応答 (人間が判読できる)
  • テキストファイルでの保存
  • ユーザーへの表示

結論

RFC 3339ISO 8601 は、異なるものの関連する目的を果たします。

  • Web API、ネットワーク プロトコル、および厳密なタイムゾーン対応タイムスタンプを必要とするシナリオには RFC 3339 を使用します
  • 一般的なデータ交換、ファイル命名、および柔軟性が必要なシナリオには ISO 8601 を使用します

どちらの標準も広くサポートされており、相互運用可能です。特定のユースケースに基づいて選択しますが、アプリケーション内の一貫性を維持してください。

関連リソース