タイムスタンプを変換する方法
Unix タイムスタンプ、ISO 8601 文字列、人が読める日付形式の間で変換します。
问题
ある形式(例:Unix エポック)のタイムスタンプを、別の形式(例:ISO 8601 やローカル時刻)にする必要があります。
前提条件
- Unix タイムスタンプの理解
- ISO 8601 形式に関する知識
ステップ
-
1. Identify the input format
Determine whether the timestamp is a Unix epoch (seconds or milliseconds since 1970-01-01), an ISO 8601 string, or a custom format. Unix timestamps in seconds are 10 digits; milliseconds are 13 digits. This distinction is critical.
入力1697254800 (seconds)输出Unix epoch in seconds -
2. Convert to the target format
Parse the timestamp into a date object, then format it as needed. For ISO 8601, use toISOString(). For human-readable, use locale-aware formatting. For Unix timestamp, use getTime()/1000 (seconds) or getTime() (milliseconds).
入力1697254800 → ISO 8601输出2023-10-14T03:00:00.000Z -
3. Handle timezones correctly
Unix timestamps are always UTC. When displaying in local time, convert explicitly. Beware of the system's local timezone affecting parsing of date strings. Always store and transmit timestamps in UTC to avoid ambiguity.
入力UTC → local time输出timezone-aware display
期待される結果
タイムゾーン処理が正しい状態で、目的の形式に変換されたタイムスタンプ。
よくあるエラー
- Confusing seconds and milliseconds
- Unix timestamps can be in seconds (10 digits) or milliseconds (13 digits). Check the magnitude and convert accordingly. JavaScript uses milliseconds.
- Timezone offset applied incorrectly
- Always work in UTC internally and convert to local time only for display. Use explicit timezone libraries for reliable conversion.
トラブルシューティング指引
- If the date is off by hours, check for a timezone mismatch between the source and your system.
- If the year is 1970, the timestamp was treated as 0 or parsed incorrectly.
セキュリティ上の制限
- Timestamp conversion is a pure calculation with no security implications.