gpt4 book ai didi

sql-server - SQL 服务器 : Convert Between UTC and Local Time Precisely

转载 作者:太空狗 更新时间:2023-10-30 01:50:58 25 4
gpt4 key购买 nike

我需要将 SQL Server 2008 R2 数据库中的几列从本地时间(SQL Server 所在的时区)转换为 UTC。

我在 StackOverflow 上看到了很多类似的问题,但答案都无法正确使用夏令时,它们只考虑了当前差异并偏移了日期。

最佳答案

我找不到任何方法单独使用 T-SQL 来完成这项工作。我使用 SQL CLR 解决了它:

public static class DateTimeFunctions
{
[SqlFunction(IsDeterministic = true, IsPrecise = true)]
public static DateTime? ToLocalTime(DateTime? dateTime)
{
if (dateTime == null) return null;
return dateTime.Value.ToLocalTime();
}

[SqlFunction(IsDeterministic = true, IsPrecise = true)]
public static DateTime? ToUniversalTime(DateTime? dateTime)
{
if (dateTime == null) return null;
return dateTime.Value.ToUniversalTime();
}
}

以及以下注册脚本:

CREATE FUNCTION ToLocalTime(@dateTime DATETIME2) RETURNS DATETIME2 AS EXTERNAL NAME AssemblyName.[AssemblyName.DateTimeFunctions].ToLocalTime; 
GO
CREATE FUNCTION ToUniversalTime(@dateTime DATETIME2) RETURNS DATETIME2 AS EXTERNAL NAME AssemblyName.[AssemblyName.DateTimeFunctions].ToUniversalTime;

被迫付出这样的努力来转换 UTC 时间是一种耻辱。

请注意,这些函数将本地时间 解释为服务器的本地时间。建议将客户端和服务器设置为同一时区以避免混淆。

关于sql-server - SQL 服务器 : Convert Between UTC and Local Time Precisely,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11063313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com