oracle將日期差轉換為時分秒格式

2021-10-20 21:41:18 字數 2293 閱讀 3684

要求:

計算2021/03/03 16:28:00-2021/03/03 14:25:01=02:02:59

如果時間差小於一天,可以用以下簡寫方法

with tab1 as

(select to_date(

'2021/03/03 16:28:00'

,'yyyy/mm/dd hh24:mi:ss')-

to_date(

'2021/03/03 14:25:01'

,'yyyy/mm/dd hh24:mi:ss'

) tim

from dual

)select to_char(trunc(sysdate)

+ t1.tim,

'hh24:mi:ss'

)from tab1 t1

;

如果時間差大於一天,並且要求多出的天加到小時上

例如2021/03/03 16:28:00-2021/03/02 14:25:01=26:02:59

with tab1 as

(select to_date(

'2021/03/03 16:28:00'

,'yyyy/mm/dd hh24:mi:ss')-

to_date(

'2021/03/02 14:25:01'

,'yyyy/mm/dd hh24:mi:ss'

) tim

from dual

)select trunc(t1.tim)*24

+ to_char(trunc(sysdate)

+ t1.tim,

'hh24')||

to_char(trunc(sysdate)

+ t1.tim,

':mi:ss'

)from tab1 t1

;

如果在之前的基礎上再要求日期差可以為負數,那麼應該這樣寫

with tab1 as

(select to_date(

'2021/03/02 14:25:01'

,'yyyy/mm/dd hh24:mi:ss')-

to_date(

'2021/03/03 16:28:00'

,'yyyy/mm/dd hh24:mi:ss'

) tim

from dual

)select decode(sign(t1.tim),-

1,'-','')

||(trunc(abs(t1.tim))*

24+ to_char(trunc(sysdate)

+ abs(t1.tim)

,'hh24'))

|| to_char(trunc(sysdate)

+ abs(t1.tim)

,':mi:ss'

)from tab1 t1

;

原理:在oracle中日期格式相減的值的單位為天,用這個天數加上各種日期函式就可以得出時分秒格式的結果。

為了使用方便,也可以將上述**封裝到函式中使用。

create

orreplace

function test_0303(p_date_num number)

return varchar2 is

v_res varchar2(50)

;begin

select trunc(p_date_num)*24

+ to_char(trunc(sysdate)

+ abs(p_date_num)

,'hh24')||

to_char(trunc(sysdate)

+ abs(p_date_num)

,':mi:ss'

)into v_res

from dual t1

;return v_res;

end;

通過函式呼叫

select test_0303(

to_date(

'2021/03/03 16:28:00'

,'yyyy/mm/dd hh24:mi:ss')-

to_date(

'2021/03/03 14:25:01'

,'yyyy/mm/dd hh24:mi:ss'))

from dual;

Oracle獲取時間間隔以及轉換為時分秒格式

1 獲取2個輸入時間的時間間隔 兩個date型別字段 start date,end date,計算這兩個日期的時間差 分別以天,小時,分鐘,秒,毫秒 天 round to number end date start date 小時 round to number end date start dat...

C 將日期轉換為時間戳(日期與時間戳互轉)

public static class abpextensions 將10位時間戳timestamp轉換成日期 public static datetime tolocaldatetime this int target 上面兩個靜態方法已經被封裝為擴充套件方法,可以在 datetime 型別和 i...

oracle 將天數 1 366 轉換為日期

在平時的應用中,我們很多地方都使用了日期函式to date 但是我們對日期函式的格式知道得很少,或者說我們根本就不會去研究它 然而,知道日期格式是多麼的重要 下面是乙個具體的應用 有一張表,有年字段year,時期欄位type,期數term,如下 id year type term 1 2010 r ...