oracle日期格式轉換

1. 日期轉化爲字符串 (以2016年10月20日爲例)字符串

select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss')  strDateTime from dual;    --獲取年-月-日 時:分:秒   
--顯示結果爲:2016-10-20 12:35:21date

select to_char(sysdate,'yyyymmdd hh24:mi:ss')  strDateTime from dual;    --獲取年月日 時:分:秒  
--顯示結果爲:20161020 13:39:25select

select to_char(sysdate,'yyyymmdd')  strDateTime from dual;     --獲取年月日 
--顯示結果爲:20161020im

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;     --獲取日  
--顯示結果爲:20co

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;

相關文章
相關標籤/搜索