我有一个包含这样数据的SQL表:
| theDate (datetime) | theValue (int) |
----------------------------------------
| 2010-05-17 02:21:10 | 5 |
| 2009-03-12 04:11:35 | 23 |
| 2010-02-19 18:16:53 | 52 |
| 2008-07-07 22:54:11 | 30 |
日期以UTC格式存储在日期时间列中,如何将它们转换为当地时间(挪威)?请记住,由于冬季/夏季,UTC-offset整年都不一样。
更新:我正在使用Microsoft SQL Server 2005,我需要从SQL执行此操作,因为数据将在稍后显示给报告。
答案 0 :(得分:3)
此声明适用于您列出的表格。使用逻辑,您可以将其应用于任何日期字段。
SELECT CASE
WHEN [theDate] BETWEEN
Convert(DATETIME, Convert(VARCHAR(4), Year([theDate])) + '-03-' + Convert(VARCHAR(2), (31 - (5 * Year([theDate])/4 + 4) % 7)) + ' 02:00:00', 20)
AND
Convert(DATETIME, Convert(VARCHAR(4), Year([theDate])) + '-10-' + Convert(VARCHAR(2), (31 - (5 * Year([theDate])/4 + 1) % 7)) + ' 03:00:00', 20)
THEN Dateadd(hh, 2, [theDate])
ELSE Dateadd(hh, 1, [theDate])
END AS [theDate],
[theValue]
FROM [YOURTABLE]
答案 1 :(得分:2)
编写CLR函数,将您的SqlDateTime从UTC转换为您的CLR本地,如下所示:
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlDateTime ToLocalTime(SqlDateTime dt)
{
try
{
return TimeZone.CurrentTimeZone.ToLocalTime(dt.Value);
}
catch
{
return SqlDateTime.Null;
}
}
答案 2 :(得分:0)
如果可以的话,使用PHP ......
$dateFormat = 'r';
$tz = 'Australia/Perth';
function convertDate($epochDate) {
global $dateFormat, $tz;
$tzOld = getenv("TZ");
putenv("TZ=$tz");
$ret = date($dateFormat, ($epochDate*1));
putenv("TZ" . ($tzOld ? "=$tzOld" : ""));
return $ret;
}
答案 3 :(得分:0)
这是我从当地时间返回当地冬令时的功能
use your_DB
go
CREATE function [dbo].[ConvertToLocalWinterTime](@instime datetime)
returns datetime
as
begin
declare @localtm datetime = @instime
declare @localwintertm datetime
declare @lastmarchsunday datetime
declare @lastoctobersunday datetime
declare @tmpmd datetime = '03.31.' + convert(char(4),year(@localtm))
declare @tmpod datetime = '10.31.' + convert(char(4),year(@localtm))
--- last sunday in march
declare @DOFWEEKM int = datepart (weekday,@tmpmd-1)
if @DOFWEEKM <7
begin
set @lastmarchsunday = @tmpmd - @DOFWEEKM
end
else
begin
set @lastmarchsunday = @tmpmd
end
----last sunday in October
declare @DOFWEEKO int = datepart (weekday,@tmpod-1)
if @DOFWEEKO <7
begin
set @lastoctobersunday = @tmpod - @DOFWEEKO
end
else
begin
set @lastoctobersunday = @tmpod
end
-------------------------------
if (@localtm > dateadd(hh,2,@lastmarchsunday)) and (@localtm < dateadd(hh,3,@lastoctobersunday))
begin
set @localwintertm = dateadd(hh,-1, @localtm)
end
else
begin
set @localwintertm = @localtm
end
return @localwintertm
end