Blog Post

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];

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating