Oracle sql query needs to change based on timezone

2019-09-16 01:24发布

I have a sql query to obtainrecords for a date range. My query works find byut when I analyzed data, I found that the records are retirved base don GMT timezone value, thus making the restults incorrect.

I get my time from a unix epoch value in database.

SELECT tableA.columnA,tableB.columnB 
FROM tableA INNER JOIN tableB ON  tableA.aId = tableB.aId 
WHERE (to_date('1970-01-01 00:00:00 +10:00','yyyy-MM-dd hh24:mi:ss') +    (tableB.epochValue/60/60/24/1000)) >  to_date('--FROM_DATE--', 'yyyy-MM-dd hh24:mi:ss') 
AND (to_date('1970-01-01 00:00:00 +10:00','yyyy-MM-dd hh24:mi:ss') + (tableB.epochValue/60/60/24/1000)) <= to_date('--TO_DATE--', 'yyyy-MM-dd hh24:mi:ss');

I want to obtain the records based on my timezone which is GMT+10 but this script gets data based on GMT timezone. I was wondering how to pass my timezone to obtain the correct date object

using http://www.epochconverter.com/, I obtained these values my epoch value - 1345079730 GMT: Thu, 16 Aug 2012 01:15:30 GMT Your time zone: Thu Aug 16 2012 11:15:30 GMT+10

My database is - Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit

1条回答
别忘想泡老子
2楼-- · 2019-09-16 01:58

Found the answer to my question.

apparently, you need to consider the time zone settings when you calculate epoch value as well

  1. add 10 hours (10*60*60*1000 milliseconds) to epoch value - epoch current value is in GMT so to make it EST (GMT+10), I added this.
  2. Used TO_TIMESTAMP_TZ instead of to_date

    SELECT tableA.columnA,tableB.columnB 
    FROM tableA INNER JOIN tableB ON  tableA.aId = tableB.aId 
    WHERE (TO_TIMESTAMP_TZ('1970-01-01 00:00:00 +10:00','yyyy-MM-dd hh24:mi:ss TZH:TZM') +    ((tableB.epochValue+(10*60*60*1000))/60/60/24/1000)) >  to_date('##FROM_DATE## +10:00', 'yyyy-MM-dd hh24:mi:ss TZH:TZM') 
    AND (TO_TIMESTAMP_TZ('1970-01-01 00:00:00 +10:00','yyyy-MM-dd hh24:mi:ss TZH:TZM') + ((tableB.epochValue+(10*60*60*1000))/60/60/24/1000)) <= to_date('##TO_DATE## +10:00', 'yyyy-MM-dd hh24:mi:ss TZH:TZM');
    
查看更多
登录 后发表回答