MySQL 8: Timestamps with timezone – Explained with examples

Updated: January 26, 2024 By: Guest Contributor Post a comment

Introduction

Working with timezones can often be challenging in application development. MySQL 8 provides a range of features to help manage timestamps effectively, even when dealing with multiple timezones. In this tutorial, we will explore the capabilities related to timestamps with timezone and go through various examples demonstrating the basic to advanced usage.

Understanding Timezones in MySQL

Before MySQL 8, the support for timezones was limited. Developers had to manually convert timestamps or rely on application-level logic. Now, MySQL includes enhanced timezone support, but it’s important to know that MySQL internally stores TIMESTAMP data in UTC. However, you can set your session or global timezone to handle the conversions automatically.

Let’s start with setting the timezone in MySQL.

SET time_zone = '+00:00';

The above query sets the session timezone to UTC. You can replace ‘+00:00’ with your desired timezone offset or a named timezone like ‘Europe/London’.

Creating a Table with a Timestamp Column

Next, let’s create a table with a timestamp column:

CREATE TABLE events (
    id INT PRIMARY KEY,
    event_name VARCHAR(50),
    event_timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

This table includes a event_timestamp column which automatically records the current timestamp when a row is inserted, based on the session’s timezone.

Inserting Data into the Table

We can insert data into our table without specifying the timestamp, letting MySQL set it for us:

INSERT INTO events (id, event_name) VALUES (1, 'Event One');

Now, if you select data, the event_timestamp will reflect the timestamp of when the row was inserted, in the session’s timezone.

SELECT * FROM events;

Converting Timezones

If you want to convert an existing timestamp from one timezone to another, you can use the CONVERT_TZ() function:

SELECT CONVERT_TZ(event_timestamp, '+00:00', 'Europe/London') as london_time FROM events;

This will convert the stored UTC timestamp to the ‘Europe/London’ timezone.

Advanced Timezone Querying

For more advanced querying, you may want to apply timezone adjustments on the fly. Let’s find all events that happened after 5 PM London time:

SELECT * FROM events
WHERE CONVERT_TZ(event_timestamp, '+00:00', 'Europe/London') > '17:00:00';

Dealing with Daylight Saving Time (DST) can also be handled automatically by using named timezones, as these contain information about DST changes.

Loading Timezone Tables

For named timezones to work, you should ensure that the timezone tables in the MySQL database are populated. You can do this by running the mysql_tzinfo_to_sql utility:

mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql

Replace ‘/usr/share/zoneinfo’ with the path to the timezone information on your server if it’s different.

Storing Timestamps with Timezone Information

Though MySQL does not store timezone information within a TIMESTAMP column, you could store it in a separate column if needed:

ALTER TABLE events ADD COLUMN timezone VARCHAR(25);

This way, you keep the timezone data along with your timestamps.

Working with Different Timezones

You may have users across different timezones and need to store and display timestamps accordingly. In this scenario, you can:

  • Store all timestamps in UTC.
  • Store the user’s timezone preference somewhere in the database or application settings.
  • Convert the timestamps to the user’s timezone when displaying them.

Timezone Best Practices

It is a common best practice to:

  • Use UTC for all internal timestamp storage.
  • Apply timezone conversions only when displaying data to users.
  • Keep your MySQL timezone data up to date with the mysql_tzinfo_to_sql utility after every DST change.
  • Make named timezones the default setting for handling DST.

Timezone Functions and Their Use Cases

Here’s a quick reference to important timezone functions in MySQL:

  • CONVERT_TZ() – Converts a timestamp from one timezone to another.
  • TIMEDIFF() – Returns the difference between two time expressions.
  • TIME_FORMAT() – Formats a time value using a specified format.
  • ADDDATE() and SUBDATE() – Add or subtract a specified time interval from a date.

Conclusion

Understanding how MySQL handles timestamps with timezone is crucial for developing applications with time-sensitive data. By using MySQL’s timezone features appropriately, you can store, retrieve, and manipulate timestamps across various timezones reliably and accurately, ensuring that your applications provide consistent and relevant temporal data to users around the world.