1. 日期轉化為字符串 (以2016年10月20日為例)
select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') strDateTime from dual; --獲取年-月-日 時:分:秒
--顯示結果為:2016-10-20 12:35:21
select to_char(sysdate,'yyyymmdd hh24:mi:ss') strDateTime from dual; --獲取年月日 時:分:秒
--顯示結果為:20161020 13:39:25
select to_char(sysdate,'yyyymmdd') strDateTime from dual; --獲取年月日
--顯示結果為:20161020
select to_char(sysdate,'yyyy') strYear from dual; --獲取年
--顯示結果為:2016
select to_char(sysdate,'mm') strMonth from dual; --獲取月
--顯示結果為:10
select to_char(sysdate,'dd') strDay from dual; --獲取日
--顯示結果為:20
select to_char(sysdate,'hh24') strHour from dual; --獲取時
--顯示結果為:13
select to_char(sysdate,'mi') strMinute from dual; --獲取分
--顯示結果為:46
select to_char(sysdate,'ss') strSecond from dual; --獲取秒
--顯示結果為:43
2. 字符串和時間互轉
select to_date('2010-10-20 13:23:44','yyyy-mm-dd hh24:mi:ss') dateTime from dual;
顯示結果:2010/10/20 13:23:44
select to_date('2010-10-20 13:23:44','yyyy/mm/dd hh24:mi:ss') dateTime from dual;
顯示結果:2010/10/20 13:23:44
select to_char( to_date(222,'J'),'Jsp') from dual;
顯示結果:Two Hundred Twenty-Two
如果按照下面的例子寫,會報錯:ORA-01849:小時值必須介於1和12之間。(因為其中的hh是12進制,沒有13所以報錯)
select to_date('2005-12-25,13:25:59','yyyy-mm-dd,hh:mi:ss') from dual;
3. 查詢某天是星期幾
select to_char(to_date('2012-10-20','yyyy-mm-dd'),'day') strDay from dual;
顯示結果:星期六
select to_char(to_date('2012-10-20','yyyy-mm-dd'),'day','NLS_DATE_LANGUAGE = English') strDay from dual;
顯示結果:saturday
4. 兩個日期間的天數
select floor(sysdate - to_date('20161010','yyyymmdd')) strTime from dual;
--其中sysdate=2016/10/20 17:10:51
--顯示結果:10
5. 時間為null的用法
select to_date(null) from dual;
6.月份差
select months_between(date'2014-04-23',date'2013-04-23') days from dual;