Liquibase: How to set the default value of a date column to be "now" in UTC format?

2 min read 07-10-2024
Liquibase: How to set the default value of a date column to be "now" in UTC format?


Liquibase: Setting Default Date Values to "Now" in UTC

Problem: You need to automatically populate a date column in your database with the current time, but you want to ensure this time is in UTC (Coordinated Universal Time) format.

Solution: Liquibase provides a simple and effective way to achieve this by utilizing its now() function and a slight tweak to the defaultValue attribute.

Scenario:

Imagine you have a table called users with a created_at column of type timestamp and you want to automatically set the current time in UTC when a new user is created.

Original code (incorrect):

<changeSet author="your-name" id="1">
  <createTable tableName="users">
    <column name="created_at" type="timestamp" defaultValue="now()">
    </column>
  </createTable>
</changeSet>

This code will populate the created_at column with the current time, but not necessarily in UTC. This is because the default behavior of the now() function varies between databases.

Explanation:

The issue lies in the defaultValue attribute. While now() returns the current time, it doesn't inherently ensure it's in UTC. Different databases might interpret now() as the current time in their respective time zones.

Solution with UTC:

To guarantee UTC time, we need to modify the defaultValue using the date() function and specify the UTC time zone:

<changeSet author="your-name" id="1">
  <createTable tableName="users">
    <column name="created_at" type="timestamp" defaultValue="date('now', 'UTC')">
    </column>
  </createTable>
</changeSet>

This code will now accurately populate the created_at column with the current time in UTC format.

Key Points:

  • date('now', 'UTC'): This combines the now() function with the date() function, specifying the UTC time zone.
  • Database-Specific Considerations: While this solution is generally applicable, some databases might require different syntax or functions for handling UTC. Consult your database documentation if you encounter issues.

Additional Value:

  • Understanding Time Zones: It's important to understand that UTC is a globally recognized standard time zone. Utilizing UTC ensures consistent timestamp values across different systems and time zones.
  • Timestamp Accuracy: Setting the default value to "now" in UTC provides better data accuracy and consistency for time-sensitive operations.

References:

By implementing this solution, you can confidently capture timestamps in UTC format, ensuring accurate and reliable data across your applications.