Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert getdate() to EST

I would like to convert getdate() in SQL Server to EST time.

like image 863
derin Avatar asked Jan 17 '11 11:01

derin


People also ask

How do I change the timezone in SQL query?

USE time_converter; Step3: Creating table times with 2 columns using the following SQL query as follows. Let us create a table with index and DATETIME as a datatype. CREATE TABLE times (Sno INT, date_time DATETIME);

What timezone does Getdate () use?

GETDATE returns the current date and time in the current session time zone (UTC by default). It returns the start date or time of the current statement, even when it is within a transaction block.


1 Answers

UPDATED ANSWER (05-29-2020)

The Azure SQL team has released a new function which makes this even easier. SELECT CURRENT_TIMEZONE_ID() will return your server's timezone. Adding this function into the ORIGINAL ANSWER below yields a single query will work globally on all Azure SQL Servers.

SELECT CONVERT(DATETIME,GETDATE() AT TIME ZONE (SELECT CURRENT_TIMEZONE_ID()) AT TIME ZONE 'Eastern Standard Time')

This query will work on any Azure SQL Server.

ORIGINAL ANSWER:

There are a lot of answers here that are unnecessarily complex, or that don't account for daylight savings time. No massive CASE statements needed. No new stored procedure, or scalar/user defined functions are needed. As of SQL Server 2016, converting between timezones can be done with a single line of native sql. This has advantages. For example, it can be called from reports or used on databases that are read-only.

SELECT CONVERT(DATETIME,GETDATE() AT TIME ZONE 'UTC' AT TIME ZONE 'Eastern Standard Time')

That's it. Above, we are using the AT TIME ZONE features, described in more detail here. There may be some functions and features that are new here, so an explanation is warranted. The query above calls GETDATE() and sets it's timezone as UTC using AT TIMEZONE. Implicitly, this is also changing it's datatype from a datetime to datetimeoffset. Next, we'll call AT TIMEZONE again to cut it over to EST. Lastly, we'll wrap the entire thing in CONVERT() to get it back to a datetime, dropping the unneeded +/- hours portion during the process.

Taking the query step-by-step ...

SELECT [GetDate]            = GETDATE()
SELECT [GetDateAtUtc]       = GETDATE() AT TIME ZONE 'UTC'
SELECT [GetDateAtUtcAtEst]  = GETDATE() AT TIME ZONE 'UTC' AT TIME ZONE 'Eastern Standard Time'
SELECT [GetDateEst]         = CONVERT(DATETIME,GETDATE() AT TIME ZONE 'UTC' AT TIME ZONE 'Eastern Standard Time')

enter image description here

like image 110
Troy Witthoeft Avatar answered Sep 20 '22 14:09

Troy Witthoeft