Mar 11, 2009

Date conversion according to timezone

We do often need to generate reports from database. Usually dates are stored in database formatted to a specific timezone - preferably in server timezone. When we retrieve those date related data, we have to format those according to users' timezone to put sense in date information.

We could easily do that using the date function NEW_TIME(). We have to need the source/base timezone and the desired timezone we want to convert.

For example, if I want to convert a date which is stored in 'US/Eastern' timezone to user's timezone 'US/Mountain' - I could do it easily in the following ways -

--To look up the timezone short names to be used in the function.
SELECT * FROM v$timezone_names;

Example - 1:

--US/Eastern to US/Mountain
SELECT TO_CHAR(REPORT_DATE, 'DD-MON-YY HH:MI:SS AM') ORIGINAL_EST, TO_CHAR(NEW_TIME(REPORT_DATE, 'EST','MST'), 'DD-MON-YY HH:MI:SS AM') "Eastern to Mountain"
FROM USER_REPORTS
WHERE rownum <4;

Example - 2:

--sysdate conversion, Central to Pacific
SELECT TO_CHAR(NEW_TIME(sysdate, 'CDT','PDT'), 'DD-MON-YY HH:MI:SS AM') "Central to Pacific"
FROM DUAL;

No comments: