在 select 语句中将 Datetime 列从 UTC 转换为本地时间

Convert Datetime column from UTC to local time in select statement(在 select 语句中将 Datetime 列从 UTC 转换为本地时间)
本文介绍了在 select 语句中将 Datetime 列从 UTC 转换为本地时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在执行一些 SQL 选择查询,并希望将我的 UTC 日期时间列转换为本地时间,以便在我的查询结果中显示为本地时间.请注意,我不希望通过代码进行此转换,而是在对我的数据库进行手动和随机 SQL 查询时.

I'm doing a few SQL select queries and would like to convert my UTC datetime column into local time to be displayed as local time in my query results. Note, I am NOT looking to do this conversion via code but rather when I am doing manual and random SQL queries against my databases.

推荐答案

您可以在 SQL Server 2008 或更高版本上执行以下操作:

You can do this as follows on SQL Server 2008 or greater:

SELECT CONVERT(datetime, 
               SWITCHOFFSET(CONVERT(datetimeoffset, 
                                    MyTable.UtcColumn), 
                            DATENAME(TzOffset, SYSDATETIMEOFFSET()))) 
       AS ColumnInLocalTime
FROM MyTable

你也可以不那么冗长:

SELECT DATEADD(mi, DATEDIFF(mi, GETUTCDATE(), GETDATE()), MyTable.UtcColumn) 
       AS ColumnInLocalTime
FROM MyTable

无论你做什么,不要使用 - 减去日期,因为该操作不是原子的,并且由于在系统日期时间和本地日期时间在不同时间检查(即非原子地).

Whatever you do, do not use - to subtract dates, because the operation is not atomic, and you will on occasion get indeterminate results due to race conditions between the system datetime and the local datetime being checked at different times (i.e., non-atomically).

请注意,此答案未考虑夏令时.如果您想包含 DST 调整,另请参阅以下 SO 问题:

Please note that this answer does not take DST into account. If you want to include a DST adjustment, please also see the following SO question:

如何创建SQL Server 中的夏令时开始和结束函数

这篇关于在 select 语句中将 Datetime 列从 UTC 转换为本地时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)