一、作用:从一个date(日期)类型或者interval(时间区间)类型中截取指定的部分。
二、范例:
获取系统当前时间
select sysdate from dual ;
SYSDATE
-----------
2016/1/3 18
分别获取对应的年月日时分秒
(1)select (to_char(sysdate,‘YYYY‘)) from dual
(2)select (to_char(sysdate,‘YEAR‘)) from dual
(1)结果:2015 (2)结果:TWENTY FIFTEEN
(1)select (to_char(sysdate,‘MM‘)) from dual
(2)select (to_char(sysdate,‘MONTH‘)) from dual
(1)结果:11 (2)结果:11月
(1)select (to_char(sysdate,‘DD‘)) from dual
(2)select (to_char(sysdate,‘DAY‘)) from dual
(1)结果:26 (2)结果:星期四
判断一个字符串是否是一个有效的时间的函数,如果是有效时间则返回1,如果不是则返回0
CREATE OR REPLACE FUNCTION xiaoxing_is_date(parameter VARCHAR2) RETURN NUMBER IS
val DATE;
BEGIN
val := TO_DATE(NVL(parameter, ‘a‘), ‘yyyy-mm-dd hh24:mi:ss‘);
RETURN 1;
EXCEPTION
WHEN OTHERS THEN
RETURN 0;
END;
select extract(year from sysdate) year from dual ;
YEAR
----------
2016
获取date中的月
select extract(month from sysdate) month from dual ;
MONTH
----------
1
获取date中的天
select extract(day from sysdate) day from dual;
DAY
----------
3
获取两个日期之间具体的时间间隔
date是常用的日期类型,时间间隔是秒,他们两个类型相减得到的时间间隔结果单位是“天”。
timestamp是date类的扩展,没有什么实质的区别,只是timestamp比date取值更精确而已。
范例:to_timestamp()
select to_timestamp(‘2015-02-15 22:22:22‘,‘yyyy-mm-dd hh24:mi:ss‘) from dual ;
TO_TIMESTAMP(‘2015-02-1522:22:
--------------------------------------------------------------------------------
15-2月 -15 10.22.22.000000000 下午
范例:to_date()
select to_date(‘2015-02-15 22:22:22‘,‘yyyy-mm-dd hh24:mi:ss‘) from dual ;
TO_DATE(‘2015-02-1522:22:22‘,‘
------------------------------
2015/2/15 22:22:22
范例:计算两个to_timestamp()的值
select to_timestamp(‘2016-02-15 22:22:22‘, ‘yyyy-mm-dd hh24:mi:ss‘) -
to_timestamp(‘2016-01-04 10:55:55‘, ‘yyyy-mm-dd hh24:mi:ss‘)
from dual;
TO_TIMESTAMP(‘2016-02-1522:22:
---------------------------------------
+000000042 11:26:27.000000000
范例:计算两个to_date()的值
select to_date(‘2016-02-15 22:22:22‘, ‘yyyy-mm-dd hh24:mi:ss‘) -
to_date(‘2016-01-04 10:55:55‘, ‘yyyy-mm-dd hh24:mi:ss‘)
from dual;
TO_DATE(‘2016-02-1522:22:22‘,‘
------------------------------
42.4767013888889
select systimestamp from dual ;
SYSTIMESTAMP
--------------------------------------------------------------------------------
03-1月 -16 07.42.08.795266 下午 +08:00
范例:
select extract(year from systimestamp) year
,extract(month from systimestamp) month
,extract(day from systimestamp) day
,extract(minute from systimestamp) minute
,extract(second from systimestamp) second
,extract(timezone_hour from systimestamp) th
,extract(timezone_minute from systimestamp) tm
,extract(timezone_region from systimestamp) tr
,extract(timezone_abbr from systimestamp) ta
from dual ;
YEAR MONTH DAY MINUTE SECOND TH TM TR TA
---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------------------------------------------------------------- ----------
2016 1 3 56 49.314124 8 0 UNKNOWN