Click here to Skip to main content
15,886,110 members
Articles / Database Development / SQL Server
Tip/Trick

Formatting Local Datetime to UTC in SQL Server

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
17 Jul 2012CPOL 28.6K   1   2
This article intends to describe a simple and elegant way of converting local datetime to UTC and store it in DB.

Introduction

We often come across requirements in our applications where we are required to store datetime in standard format. Such requirements mainly arise when an application is used by users across multiple geographies. This article intends to describe a simple and elegant way of converting local datetime to UTC and store it in the DB.

Background

We had an application where data was entered by users from multiple geographies. The challenge was to store datetime in a standard format irrespective of time zone. For each entry when the time exceeded 1 hour, a file was to FTP'ed.

Using the code

This code can be directly used inside any proc in MS SQL Server.

SQL
Create Function dbo.[ChangeLocalTimeToUTC]
(
    @CurrentServerDateTime as DateTime,
    @CurrentUTCDateTime as DateTime,
    @LocalTimeToChange as Datetime
)
Returns DateTime

Begin
    Declare @ServerTime Datetime    
    Set @ServerTime = @CurrentServerDateTime

    Declare @UTCTime Datetime
    Set @UTCTime = @CurrentUTCDateTime

    Declare @Offset int
    set @Offset = DateDiff(second,@ServerTime,@UTCTime)

    Declare @ConvertedUTCTime Datetime
    Set @ConvertedUTCTime = DateAdd(second,@Offset,@LocalTimeToChange)

    Return @ConvertedUTCTime 
End

Points of Interest

This requirement highlighted a peculiar problem faced by the application that span multiple geographies in the currently globalized world. It also brought to the fore the use of standard timezone neutral format.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
I have more than 5 yrs of work ex as a software developer for a Financial Consulting firm and an Investment bank. My technical expertise include C# programming,WPF,WCF, SSRS reporting,ASP.Net and MS SQL (2005 & 2008).

Comments and Discussions

 
QuestionDaylight Saving Time ... Pin
tb6022-Jul-20 19:41
tb6022-Jul-20 19:41 
GeneralMy vote of 4 Pin
OzarkMountainMan17-Jul-12 9:46
OzarkMountainMan17-Jul-12 9:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.