oracle时间类型、时区及其函数

一、oracle时间类型

oracle有date、timestamp、interval year to month和interval day to sesond四种类型,可通过nls_date_format来设置我们想要的日期格式。

1、date存储年月日时分秒,固定存储7字节

select sysdate,current_date from dual;

2、timestamp除了存储年月日时分秒,还有小数秒,小数秒默认6位,timestamp(6)表示秒的小数点后面可以存储6位,后面还带有时区,是timestamp with time zone。

select systimestamp,current_timestamp from dual;

3、interval year[year_precision] to month存储年-月的时间间隔,通过year_precision来指定年的精度

interval '1' year时间间隔是1年;interval '14' month时间间隔是14个月;interval '0-5' year to month时间间隔是0年5个月;interval '123' year(3) to month时间间隔123年,精度为3位。

 参考链接:https://www.cnblogs.com/rusking/p/4599599.html

 

4、interval day[day_precision] to second[sec_precision]存储天-秒的时间间隔

interval '3' day时间间隔是3天;interval '2' hour时间间隔是2个小时;interval '123 2:25:45.12' day(3) to second(2)时间间隔是123天零2小时25分钟45.12秒,天的精度是3位,秒的精度是2位。

参考链接:https://www.cnblogs.com/cz-xjw/p/5177888.html

 

二、时区

地球自转是自西向东,故西方比东方时间晚,因此从西向东的时区是依次递增的,UCT+1->UCT+8...,东加西减,中国是东八区,英国是零时区,除了夏令时中国比英国快8个小时,因为夏令时英国把时间调快1小时,所以夏令时中国比英国快7小时。

1、sysdate是获取数据库所在操作系统的时间,与数据库或会话无关系,在session建立时与服务端同步。current_date返回数据库会话所设置的本地时区,在session建立时与客户端同步,可通过alter session set time_zone='+08:00'修改。

2、sessiontimezone与客户端session所在操作系统一直,可通过alter session set time_zone='+08:00'修改,dbtimezone为数据库的时区。

select sessiontimezone,dbtimezone from dual;

alter session set time_zone='+09:00';  //将时区从8区调整为东9区,current_date就是原来时间+1
select sysdate,current_date from dual;

 

三、相关函数

1、tz_offset()是oracle根据时区名称,返回时区与0时区相差的小时和分钟数。

select * from v$timezone_names;  //tzname是时区名称
select tz_offset('Asia/Shanghai'),tz_offset('America/New_York'),tz_offset('Europe/London')from dual; 
//查看上海、纽约、伦敦与0时区相差的分钟数,按理说伦敦应该是0时区,但夏令时会把时间往前调1个小时所以变成+1

 

2、from_tz()将时间戳和时区转换成具有时区值的时间戳

 select current_timestamp,from_tz(current_timestamp,'Asia/Shanghia') from dual;  //因为current_timestamp本身就带有时区,该语句会出现 expected TIMESTAMP got TIMESTAMP WITH TIME ZONE

第一个参数就是不带时区的时间戳,如果带时区就会出错

select from_tz(timestamp '2022-08-25 14:11:30','Asia/Shanghai') from dual;

 

3、to_timestamp将各类型的时间转为时间戳类

select to_timestamp('20220825','yyyy-mm-dd hh24:mi:ss.ff') from dual;

 

4、to_yminterval()将字符串类型转为 interval year to month类型,可用于年月的加减

select sysdate,sysdate+to_yminterval('02-08') in2y_8m,sysdate+to_yminterval('0-8')in8m from dual;  //算出与系统时间相差2年8个月,8个月的时间

 

5、to_dsinterval()将字符串类型转为inter day to second类型,可用于日-秒的加减

select sysdate,sysdate+to_dsinterval('31 08:12:25') ds1,sysdate+to_dsinterval('0 00:00:08')ds2 from dual;

 

posted @ 2022-08-25 14:33  微风徐徐$  阅读(6704)  评论(0编辑  收藏  举报