使用 DBTimeZone 察看数据库所在的时区
SQL> select dbtimezone from dual;
DBTIMEZONE
----------
+08:00
找2个典型的美国时区
SQL> select tz_offset('US/Eastern'),tz_offset('US/Mountain') from dual;
TZ_OFFSET('US/EASTERN') TZ_OFFSET('US/MOUNTAIN')
----------------------- ------------------------
-05:00 -07:00
建立表,包含不同类型的三个column
create table tstz(ts timestamp, tstz timestamp with time zone, tsltz timestamp with local time zone);
insert into tstz values(systimestamp,systimestamp,systimestamp);
commit;
下面构造一个场景,用三个不同的时区的session来查询同样的数据
SQL>
SQL> alter session set NLS_TIMESTAMP_TZ_FORMAT = 'yyyy/mm/dd hh24:mi:ssxff TZH:TZM';
SQL> alter session set NLS_TIMESTAMP_FORMAT = 'yyyy/mm/dd hh24:mi:ssxff';
使用 SessionTimeZone 察看当前session的时区信息
SQL> select sessiontimezone from dual;
SESSIONTIMEZONE
---------------------------------------------------------------------------
+08:00
SQL> select * from tstz;
TS TSTZ TSLTZ +08:00
------------------------------------------------- ------------------------------------------------- -------------------------------------------------
2008/03/29 10:14:10.774754 2008/03/29 10:14:10.774754 +08:00 2008/03/29 10:14:10.774754
SQL> alter session set time_zone = 'US/Mountain';
SQL> select * from tstz;
TS TSTZ TSLTZ -07:00
------------------------------------------------- ------------------------------------------------- -------------------------------------------------
2008/03/29 10:14:10.774754 2008/03/29 10:14:10.774754 +08:00 2008/03/28 19:14:10.774754
SQL> alter session set time_zone = 'US/Eastern';
SQL> select * from tstz;
TS TSTZ TSLTZ -05:00
------------------------------------------------- ------------------------------------------------- -------------------------------------------------
2008/03/29 10:14:10.774754 2008/03/29 10:14:10.774754 +08:00 2008/03/28 21:14:10.774754
从 高亮部分可以发现
timestamp with time zone 保存了insert的时区, 并且不 论在什么地方查询,显示结果都是一致的
timestamp with local time zone 保存的是一个内部的时区信息, 在不同 时区进行查询,都会自动转换成当前时区进行显示。
因为修改了session的时 区信息,所以系统时区和当前session时区不同
SQL> select systimestamp, current_timestamp, localtimestamp from dual;
SYSTIMESTAMP CURRENT_TIMESTAMP LOCALTIMESTAMP
------------------------------------------------- ------------------------------------------------- -------------------------------------------------
2008/03/29 15:59:37.400640 +08:00 2008/03/29 02:59:37.400646 -05:00 2008/03/29 02:59:37.400646