I have developed 2 SQL functions for this:
1create function utc_to_local_datetime
2(
3 @utc_date_time date_time ,
4 @time_zone_id time_zone
5)
6returns date_time
7as
8begin
9
10
11 DECLARE @offset_minutes AS INT
12
13 SET @time_zone_id = COALESCE(@time_zone_id, dbo.get_user_setting('time_zone_id', NULL), 'Central European Standard Time')
14
15 SET @offset_minutes = (SELECT CAST((LEFT(offset, 1) + '1') AS INT) * DATEDIFF(MINUTE, '1/1/1900', CAST(right(offset, 5) AS DATETIME)) FROM (SELECT offset = RIGHT(CONVERT(DATETIME, @utc_date_time) AT TIME ZONE @time_zone_id, 6)) x)
16
17 RETURN DATEADD(MINUTE, @offset_minutes, @utc_date_time)
18
19
20end
21go
22
23grant execute on utc_to_local_datetime to public
24go
25
1create function local_to_utc_datetime
2(
3 @date_time date_time ,
4 @time_zone_id time_zone
5)
6returns date_time
7as
8begin
9
10 DECLARE @raw_offset_minutes AS INT
11
12 SET @raw_offset_minutes = (SELECT CAST((LEFT(offset, 1) + '1') AS INT) * DATEDIFF(MINUTE, '1/1/1900', CAST(right(offset, 5) AS DATETIME)) FROM (SELECT offset = RIGHT(CONVERT(DATETIME, @date_time) AT TIME ZONE @time_zone_id, 6)) x)
13
14 RETURN DATEADD(MINUTE, -1 * @raw_offset_minutes, @date_time)
15
16
17
18
19
20end
21go
They work fine, but it is still hard to let them work for al scenarios. For example a user in Japan, who wants to schedule a task in Brazil 6 months in advance.
A local time control would be very welcome. Solving the problem with SQL is possible, but sometimes has serious impact on performance.