Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / SQL-Server

Formatting Local Datetime to UTC in SQL Server

4.00/5 (1 vote)
17 Jul 2012CPOL 29K  
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)