Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time zone conversion in SQL query

I am using a query to get some application Received Date from Oracle DB which is stored as GMT. Now I have to convert this to Eastern standard/daylight savings time while retrieving. I am using the below query for this:

   select to_char (new_time(application_recv_date,'gmt','est'), 'MON dd, YYYY') from application

It works fine for Standard time. But for daylight savings time we need to convert it to 'edt' based on timezone info. I am not very sure on how to do this. Please help me out

like image 840
satyanarayana Avatar asked Apr 08 '14 09:04

satyanarayana


People also ask

How do I convert UTC time to local time in SQL?

SELECT CONVERT(datetime, SWITCHOFFSET(CONVERT(DATETIMEOFFSET, GETUTCDATE()), DATENAME(TZOFFSET, SYSDATETIMEOFFSET()))) AS LOCAL_IST; Here, the GETUTCDATE() function can be used to get the current date and time UTC. Using this query the UTC gets converted to local IST.

How do I display timezone in SQL?

For SQL Managed Instance, return value is based on the time zone of the instance itself assigned during instance creation, not the time zone of the underlying operating system. For SQL Database, the time zone is always set to UTC and CURRENT_TIMEZONE returns the name of the UTC time zone.

How do I convert UTC to Central time in SQL?

If you only need to convert from UTC to CST. You can simply use DATEADD(hour, -6, Timestamp) in your query.


1 Answers

You can use this query, without having to worry about timezone changes.

select to_char(cast(application_recv_date as timestamp) at time zone 'US/Eastern',
               'MON dd, YYYY'
              )
from application;

Ex:

EDT:

select cast(date'2014-04-08' as timestamp) d1,
       cast(date'2014-04-08' as timestamp) at time zone 'US/Eastern' d2
from dual;

D1                                 D2
---------------------------------- -------------------------------------------
08-APR-14 12.00.00.000000 AM       07-APR-14 08.00.00.000000 PM US/EASTERN

EST:

select cast(date'2014-12-08' as timestamp) d1,
       cast(date'2014-12-08' as timestamp) at time zone 'US/Eastern' d2
from dual;

D1                                 D2
---------------------------------- -------------------------------------------
08-DEC-14 12.00.00.000000 AM       07-DEC-14 07.00.00.000000 PM US/EASTERN

UPDATE:

Thanks to Alex Poole for reminding that, when timezone is not specified, local timezone is used for conversion.

To force the date to be recognized as GMT, use from_tz.

from_tz(cast(date'2014-12-08' as timestamp), 'GMT') at time zone 'US/Eastern'
like image 101
Noel Avatar answered Sep 20 '22 15:09

Noel