UTC vs Local Time
Understand the difference between UTC and local time in software development. Learn when to use each, storage best practices, and conversion strategies.
Concept
UTC+0
Detailed Explanation
UTC (Coordinated Universal Time) is the global time standard that does not observe daylight saving time and has no timezone offset. Local time is UTC adjusted by a region's timezone offset and DST rules. Understanding when to use each is crucial for building software that works correctly across timezones.
The golden rule: Store in UTC, display in local time. This principle prevents nearly every common timezone bug.
Why UTC for storage:
Server A (US East): 2024-01-15 04:30:00 EST
Server B (UK): 2024-01-15 09:30:00 GMT
Server C (Japan): 2024-01-15 18:30:00 JST
All stored as: 2024-01-15T09:30:00Z (UTC)
If each server stored its local time, comparing or ordering events across servers would require knowing each server's timezone at the time of the event. By storing UTC, every timestamp is directly comparable without any conversion.
When local time is appropriate:
There are rare cases where you should store local time: appointment scheduling (a dentist appointment at "3 PM" should stay at 3 PM even if DST rules change), recurring events in the user's timezone, and legal/regulatory timestamps that must reflect wall-clock time in a specific jurisdiction.
Conversion in code:
// JavaScript: UTC to local display
const utcDate = new Date("2024-01-15T09:30:00Z");
utcDate.toLocaleString("en-US", { timeZone: "America/New_York" });
// "1/15/2024, 4:30:00 AM"
# Python: UTC to local
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
utc_dt = datetime(2024, 1, 15, 9, 30, tzinfo=timezone.utc)
local_dt = utc_dt.astimezone(ZoneInfo("America/New_York"))
Common pitfalls:
Never rely on the server's system timezone for business logic. Two deployments of the same code can produce different results if their system timezones differ. Always specify timezones explicitly in code. Use the IANA timezone database names (America/New_York, not EST) because abbreviations are ambiguous and do not account for DST transitions.
Use Case
Distributed microservices must always store event timestamps in UTC so that logs from services running in different cloud regions can be correlated chronologically without timezone confusion.