在Oracle中使用from_tz时避免夏令时造成的异常

Oracle 中的from_tz函数,可以将一个timstamp和timzone拼成一个timestamp with timezone

SQL> select from_tz(to_timestamp('20090102','YYYYMMDD'), 'America/Sao_Paulo') from dual;
 
FROM_TZ(TO_TIMESTAMP('20090102
--------------------------------------------------------------------------------
02-1月 -09 12.00.00.000000000 上午 AMERICA/SAO_PAULO

 

但如果这个timestamp在指定的时区内不存在(比如由于夏令时,时钟往前拨了一个小时),就会抛Exception

SQL> select from_tz(to_timestamp('20091101','YYYYMMDD'), 'America/Sao_Paulo') from dual;
 
select from_tz(to_timestamp('20091101','YYYYMMDD'), 'America/Sao_Paulo') from dual
 
ORA-01878: 在日期时间或间隔中没有找到指定的字段

 解决办法嘛,先取出时区的offset,用其构建好timestamp with timezone后再转回指定的时区就好了

SQL> select from_tz(to_timestamp('20091101','YYYYMMDD'), tz_offset('America/Sao_Paulo')) at TIME ZONE 'America/Sao_Paulo' from dual;
 
FROM_TZ(TO_TIMESTAMP('20091101
--------------------------------------------------------------------------------
31-10月-09 11.00.00.000000000 下午 AMERICA/SAO_PAULO
 

 

你可能感兴趣的:(oracle,sql)