1. 程式人生 > >字串轉換to_char()、to_date()及trunc()的用法;

字串轉換to_char()、to_date()及trunc()的用法;

一、to_char()

1.基本語法

to_char(value,'format') value是待轉化的值,'format' 是轉化後的 pattern

(1)日期格式轉化

select to_char(sysdate,'yyyy') from dual;-------執行結果:2018
select to_char(sysdate,'yyyy-mm-dd') from dual;-----執行結果:2018-06-14
select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') from dual;-----執行結果:2018-06-14 15:49:02
select to_char(sysdate,'d') from dual;------執行結果:5,當前是本週的第5天(週日是第一天)
select to_char(sysdate,'iw') from dual;-----執行結果:24,當前是本年的第24周

(2)處理數字

select to_char(88877) from dual;------執行結果:88877
select to_char(1234567890,'099999999999999')  from dual;------執行結果:000001234567890,系統會自動補全位數
select to_char(12345678,'999,999,999,999')  from dual;--------執行結果:12,345,678,系統會自動補全位數
select to_char(1234567890,'999,999,999,999.9999')  from dual;-----執行結果:1,234,567,890.0000,系統會自動補全位數

(3)to_char(salary,'$99,99');

select TO_CHAR(123,'$99,999.9') from dual;

(4)用於進位制轉換:將10進位制轉換為16進位制;

select to_char(4567,'xxxx') from dual;
select to_char(123,'xxx') from dual;

二、to_date()

to_date("要轉換的字串","轉換的格式")   兩個引數的格式必須匹配。

select to_char(sysdate,'yy-mm-dd hh24:mi:ss') from dual   //顯示:08-11-07 13:22:42
select to_date('2005-12-25,13:25:59','yyyy-mm-dd,hh24:mi:ss') from dual //顯示:2005-12-25 13:25:59

三、trunc()

(1)處理日期

    語法格式:TRUNC(date[,fmt])

  其中:date 一個日期值;fmt 日期格式。

    該日期將按指定的日期格式擷取;忽略它則由最近的日期擷取。

   select trunc(sysdate) from dual;--14-6月 -18,返回當前時間
   select trunc(sysdate,'yy') from dual;--01-1月 -18,返回當年第一天
   select trunc(sysdate,'mm') from dual;--01-6月 -18,返回當月的第一天
   select trunc(sysdate,'d') from dual;--10-6月 -18,返回當前星期的第一天,即星期天
   select trunc(sysdate,'dd') from dual;--14-6月 -18,返回當前日期,今天是2018-06-14
   select trunc(sysdate,'iw') from dual;--11-6月 -18,返回當前星期的第一天,即星期一
(2)處理number型數字

    語法格式:TRUNC(number[,decimals])

    其中: number 待做擷取處理的數值;decimals 指明需保留小數點後面的位數,可選項,忽略它則截去所有的小數部分。

   注意:擷取時並不對資料進行四捨五入

    select trunc(123.567,2) from dual;--123.56,將小數點右邊指定位數後面的截去;
    select trunc(123.567,-2) from dual;--100,第二個引數可以為負數,表示將小數點左邊指定位數後面的部分截去,即均以0記;
    select trunc(123.567) from dual;--123,預設截去小數點後面的部分;

四、總結to_char、to_date和trunc在日期上的作用

(1)to_char和to_date是日期格式的轉換函式,其作用就是將目標日期以我們想要的格式顯示出來;

         舉例說明:以當前日期為例(sydate)

select to_char(sysdate,'yyyy-mm-dd')  from dual;

          只是將當前日期的格式由‘date型別’轉化為‘字元型別’,結果本身沒發生變化;

select to_date('2018-06-15','yyyy-mm-dd')  from dual;

          只是將‘字元型別’轉化為‘date型別’,‘結果本身沒有發生變化;

(2)trunc是根據目標日期擷取我們想要的日期

          舉例說明:以當前日期為例(sydate)

select trunc(sysdate,'iw') from dual;--11-6月 -18,返回當前星期的第一天,即星期一
        根據當前日期計算出本週第一天然後提取顯示,顯示結果發生變化;