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

This entry was posted in SQL Server 2008. Bookmark the permalink.

One Response to Some SQL Server Date and Time Examples

  1. Dukagjin says:

    Simple and nice examples!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s