Database
December 20, 20239 min read

Database Timestamp Storage: UTC vs Local Time Strategies

share:

Introduction

Choosing the right timestamp storage strategy is crucial for maintaining data consistency and avoiding timezone-related bugs. This guide explores different approaches and their trade-offs.

Strategy 1: Store Everything in UTC

This is the most recommended approach for most applications.

Advantages

  • Consistent reference point across all data
  • Eliminates timezone conversion bugs in storage layer
  • Simplifies data analysis and reporting
  • Works well with distributed systems

Implementation

-- PostgreSQL
CREATE TABLE events (
  id SERIAL PRIMARY KEY,
  name VARCHAR(255),
  event_time TIMESTAMP WITH TIME ZONE,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- MySQL
CREATE TABLE events (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(255),
  event_time TIMESTAMP,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Strategy 2: Store with Timezone Information

Store both the timestamp and the original timezone.

CREATE TABLE user_events (
  id SERIAL PRIMARY KEY,
  event_time_utc TIMESTAMP,
  original_timezone VARCHAR(50),
  created_at TIMESTAMP DEFAULT NOW()
);

Best Practices

  1. Always store in UTC when possible
  2. Use TIMESTAMP WITH TIME ZONE in PostgreSQL
  3. Document your timezone handling strategy
  4. Consider business requirements for historical accuracy
  5. Test with different timezones and DST transitions

Common Mistakes to Avoid

  • Storing local times without timezone information
  • Mixing UTC and local times in the same column
  • Not handling DST transitions properly
  • Forgetting to convert for display purposes