UTC vs Local Time Methods
You'll learn when to use local time getters like getHours() versus UTC getters like getUTCHours(), and why the distinction matters.
The Two Perspectives on Time
JavaScript's Date object provides two sets of methods for extracting date and time components: local methods and UTC methods. Think of them like asking "What time is it?" versus "What time is it in London right now?"
When you create a Date, it stores a single moment in time (milliseconds since epoch). But when you read that date, you can view it through two lenses:
- Local methods (
getFullYear(),getMonth(),getDate(),getHours(), etc.) return values adjusted to your computer's timezone - UTC methods (
getUTCFullYear(),getUTCMonth(),getUTCDate(),getUTCHours(), etc.) return values in Coordinated Universal Time, ignoring your timezone
When to Use Which
const now = new Date();
console.log(now.getHours()); // e.g., 15 (3 PM in your timezone)
console.log(now.getUTCHours()); // e.g., 20 (8 PM UTC)
Use local methods when:
- Displaying times to users (they expect their timezone)
- Working with user-scheduled events
Use UTC methods when:
- Storing timestamps in databases
- Comparing dates across timezones
- Building APIs that serve global users
- You need consistency regardless of server location
The difference can be hours apart! If you're in New York (UTC-5), getHours() and getUTCHours() will differ by 5 hours. This can cause bugs where dates appear "off by one day" when crossing midnight boundaries.
Key Takeaway: Local methods reflect the user's timezone; UTC methods give timezone-independent values. Use UTC for storage and comparison, local for display.