views:

232

answers:

2

Hi,

i want to loop over a period of time in tsql, and print the utc datetimes and our local variant. We live in UTC +1, so i could easily add 1 hour, but in the summertime we live in UTC +2.

In C# i can create a datetime and use a method to ask for the UTC variant and vice versa.

Till now i have this:

declare @counter int
declare @localdate datetime
declare @utcdate datetime
 set @counter = 0
 while @counter < 100
 begin
   set @counter = @counter + 1
   print 'The counter is ' + cast(@counter as char)
  set @utcdate  = DATEADD(day,@counter,GETUTCDATE())
  --set @localdate = ????

  print  @localdate  
  print @utcdate
 end
+1  A: 

GETUTCDATE() just gives you the current time in UTC, any DATEADD() you do to this value will not include any daylight savings time shifts.

Your best bet is build your own UTC conversion table or just use something like this:

http://www.codeproject.com/KB/database/ConvertUTCToLocal.aspx

KM
wow. I hope someone comes up and tell me that this isn't true that sql server can't do this?
Michel
SQL Server can't do it out of the box, you'll need to build your own function or populate your own look up table
KM
+1  A: 

Assuming you are using SQL 2005 upwards, you can develop a SQL CLR function to take a UTC date and convert to the local date.

This link is an MSDN How-To explaining how you can create a scalar UDF in C#.

Create a SQL function along the lines of

[SqlFunction()]
public static SqlDateTime ConvertUtcToLocal(SqlDateTime utcDate) 
{
    // over to you to convert SqlDateTime to DateTime, specify Kind
    // as UTC, convert to local time, and convert back to SqlDateTime
}

Your sample above would then become

set @localdate = dbo.ConvertUtcToLocal(@utcdate)

SQL CLR has its overheads in terms of deployment, but I feel cases like this are where it fits in best.

Neil Moss
thanks, gonna try that, i'll let you know
Michel
figured out how to convert utc to other timezones, AND tried to implement a SqlCLR function. Combining them however did not work, because i'm using the TimeZoneInfo object to calculate the difference datetimes, and i can't reference the assembly that class is in from my SqlProject (as it seems you can only reference a subset of the .net framework)
Michel
OK - curious as to why you need the TimeZoneInfo class given your requirement of converting UTC to Local. If your SQL server is configured as being in _your_ local time zone (agreed - this is a constraint), then your c# function becomes something like 'return new SqlDateTime(utcDate.Value.toLocalTime());' . You don't need to specify a time zone.Have I mis-understood?
Neil Moss
you're right, but it has to work for different users at different timezones
Michel
At the end: didn't find a way to do it without hardcoding.Marked as answer for the effort Neil has done.
Michel