Guides

Guide des Timestamps UTC

Cette page est provisoirement disponible en anglais. La traduction française est en préparation.

Introduction

UTC (Coordinated Universal Time) is the standard time reference used in computing and networks. Understanding how to work with UTC timestamps is essential for building applications that work across multiple timezones and need precise time calculations.

Understanding UTC

What is UTC Time?

UTC is a time standard that:

  • Has no timezone offset (no daylight saving time)
  • Uses a 24-hour clock format (00:00:00 to 23:59:59.999)
  • Represented as "Z" in ISO 8601 (e.g., 2025-01-07T12:00:00.000Z)
  • Serves as the basis for all other timezones

UTC vs Local Time

Crucial Concept: Local time varies by geographic location and timezone. UTC is constant worldwide.

CharacteristicUTC TimeLocal Time
Timezone OffsetAlways UTC+00:00Varies by location (e.g., UTC-5, UTC+8, UTC-10)
Daylight SavingNo DST adjustmentsVaries by season and region
ConsistencyGlobally consistentDifferent systems may have different local times
Primary Use CaseGlobal systems, databases, APIsUser-facing applications, calendar events
Storage SizeSame as any timestamp (no extra overhead)Same as DateTime (larger storage)
Query PerformanceExcellent (numeric comparisons)Slow (requires datetime parsing)

Warning: Always store UTC timestamps in your database. Convert to local time only for display purposes.

UTC Timestamp Format

ISO 8601

UTC timestamps in ISO 8601 always end with "Z":

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

Unix Timestamp

UTC timestamps are the number of seconds since Unix epoch (1970-01-01 00:00:00 UTC):

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

Converting UTC to Local Time

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

Python

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;

Best Practice: Always store UTC timestamps. Use application-level timezone conversion for display only.

Timezone Handling

Understanding Timezone Offsets

Timezone offsets are expressed as:

  • UTC+XX:00 (e.g., UTC-5:00)
  • UTC-XX:00 (e.g., UTC+8:00)
OffsetHoursCityRegion
UTC-5:00-5New York, Toronto, Bogota, LimaEastern Standard Time
UTC-8:00-8Los Angeles, San Francisco, TijuanaPacific Standard Time
UTC+0:000London, Dublin, LisbonWestern European Time
UTC+1:00+1Paris, Berlin, RomeCentral European Time
UTC+8:00+8Singapore, Hong Kong, PerthChina Standard Time
UTC+9:00+9Tokyo, Seoul, PyongyangJapan Standard Time
UTC+10:00+10Sydney, Melbourne, BrisbaneAustralian Eastern Standard Time
UTC+12:00+12AucklandNew Zealand Standard Time

Timezone Conversion Examples

JavaScript Timezone Conversions

// 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}")

Best Practices

UTC Storage Guidelines

Storage: Always store UTC timestamps. They are timezone-agnostic and efficient for global applications.

Display: Convert to local timezone only at the UI layer. Never store local times back to the database.

Queries: Always filter and sort by UTC timestamps. This ensures consistent ordering regardless of user's timezone.

APIs: Always use UTC timestamps in API responses. Document timezone in API documentation.

Critical Warning: Never mix UTC timestamps with local timestamps in the same column. This creates data integrity issues and query inconsistencies.

Common Pitfalls

Pitfall 1: Forgetting About Timezones

Problem: Not all locations observe DST at the same time.

Example: Arizona doesn't observe DST, but New York does. This can cause 1-hour differences between them during certain periods.

Solution: Use IANA timezone databases (tz database) which include historical and current DST rules.

Pitfall 2: Incorrect Timezone Offsets

Problem: Using hardcoded offsets instead of timezone names.

Bad: const offset = -5 * 3600000; // EST is always -5, but Arizona doesn't observe DST

Good: const offset = 'America/New_York'; // Uses IANA database with correct historical DST

Pitfall 3: Assuming All Times Are in Same Format

Problem: Not all systems use UTC (e.g., some use GMT, others use UTC+X).

Example: Unix timestamps are always UTC-based, but file systems may vary.

Solution: Always specify timezone explicitly when parsing user input.

Working with Different Timezones

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'),
];

Python

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}")

Timezone Best Practices

Timezone Selection Guidelines

<ol> <li>Always use IANA timezone names (e.g., "America/New_York", "Europe/London")</li> <li>Use timezone databases (IANA tz database, tz database) instead of hardcoded offsets</li> <li>Test DST transitions in your target regions (especially spring and fall)</li> <li>Document your timezone assumptions clearly in API documentation</li> <li>Consider using UTC for all internal storage and calculations</li> <li>Display timezone names and local times separately in UI (store UTC internally)</li> </ol>

Tools and References

Related Tools

Summary

Key Takeaway: Always store UTC timestamps. Handle timezone conversion at the application or query layer. This ensures data consistency and makes your application globally compatible.

Critical: Never mix UTC and local timestamps in database storage. Always store UTC and convert to local only when needed.

Performance Tip: UTC timestamps are ideal for:

  • Database indexing (numeric comparisons)
  • Range queries (numeric filters)
  • Sorting operations (numeric order)
  • Time-based partitioning

Code Examples Repository

For more timestamp and timezone code examples, see our related tools and guides for working with specific use cases:

Essayez

Testez votre conversion de timestamp

Résultat de date

Besoin de plus d'options ? Timestamp actuel