Home >Database >Mysql Tutorial >How to Convert a UTC Datetime Column to Local Time in SQL?
Efficiently Converting UTC Datetime to Local Time in SQL Queries
Many database systems store timestamps in UTC for consistency. This guide demonstrates how to convert these UTC datetime columns to local time directly within your SQL queries, eliminating the need for external code.
SQL Server 2008 and Later:
This approach leverages the SWITCHOFFSET
function for precise conversion:
<code class="language-sql">SELECT CONVERT(datetime, SWITCHOFFSET(CONVERT(datetimeoffset, MyTable.UtcColumn), DATENAME(TzOffset, SYSDATETIMEOFFSET()))) AS ColumnInLocalTime FROM MyTable</code>
Alternative (Verbose) Method:
A more straightforward, though less elegant, method uses DATEADD
and DATEDIFF
:
<code class="language-sql">SELECT DATEADD(mi, DATEDIFF(mi, GETUTCDATE(), GETDATE()), MyTable.UtcColumn) AS ColumnInLocalTime FROM MyTable</code>
Key Considerations:
-
) can yield unpredictable results because of potential race conditions. The methods above avoid this issue.This information empowers you to perform efficient and accurate UTC-to-local time conversions directly within your SQL queries.
The above is the detailed content of How to Convert a UTC Datetime Column to Local Time in SQL?. For more information, please follow other related articles on the PHP Chinese website!