Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 

Some SQL Server Date and Time Examples

I had a question from a developer yesterday about how to calculate the difference between local time (on the database server), and UTC Time. This needed to work in SQL Server 2005. It turns out that this is pretty easy to do in T-SQL, even in SQL Server 2005. I thought I would share these examples of what I was playing around with yesterday.

    -- SQL Server Date and Time Samples
    -- Glenn Berry 
    -- May 2010
    -- http://glennberrysqlperformance.spaces.live.com/
    -- Twitter: GlennAlanBerry
    
    -- Different ways to get date and time
    SELECT SYSDATETIME() AS [SYSDATETIME], SYSDATETIMEOFFSET() AS [SYSDATETIMEOFFSET],
           SYSUTCDATETIME() AS [SYSUTCDATETIME], CURRENT_TIMESTAMP AS [CURRENT_TIMESTAMP],
           GETDATE() AS [GETDATE], GETUTCDATE() AS [GETUTCDATE];

    -- SQL Server 2008 and 2008 R2 only
    SELECT SYSUTCDATETIME() AS [UTCTime];
    SELECT SYSDATETIMEOFFSET() AS [SysDateTimeOffset]; 
    SELECT SYSDATETIME() AS [SysDateTime] 


    -- These work in SQL Server 2005
    SELECT CURRENT_TIMESTAMP AS [CurrentTime];
    SELECT GETDATE() AS [LocalDate];
    SELECT GETUTCDATE() AS [UTCDate];  
    
    -- Getting difference between local time and UTC time
    -- This works in SQL Server 2005
    DECLARE @OffsetValue int;
    SET @OffsetValue = (SELECT DATEDIFF(hh, GETUTCDATE(), GETDATE()));
    SELECT @OffSetValue AS [TimeOffset];

Comments

Posted by Dukagjin Maloku on 7 May 2010

Simple and nice examples!

Posted by Anonymous on 7 May 2010

Pingback from  Twitter Trackbacks for                 SQL Server Central, Some SQL Server Date and Time Examples - Glenn Berry's SQL Server Performance         [sqlservercentral.com]        on Topsy.com

Posted by R.P.Rozema on 13 May 2010

The difference should be retrieved in minutes, not hours. New Delhi (India) local time for example is at UTC/GMT +5:30 hours. A correct example is:

-- Getting difference between local time and UTC time

   -- This works in SQL Server 2005

   DECLARE @OffsetValue int;

   SET @OffsetValue = (SELECT DATEDIFF(minute, GETUTCDATE(), GETDATE()));

   SELECT @OffSetValue AS [TimeOffset];

Posted by Glenn Berry on 13 May 2010

R.P.,

Yes, your variation is a good idea for non-US time zones. Thanks!

Leave a Comment

Please register or log in to leave a comment.