在 oracle 计算两个时间差 换算成 xx天xx时xx分xx秒 的形式
在百度之后 发现 这两个 to_timestamp 和 extract 函数是比较合适的
准换时要用 to_timestamp 不要 用to_date
区别是:由于oracle中date类型只支持到秒,不支持到毫秒,所以to_date()不能取到毫秒。如果要取到毫秒,oracle 9i以上版本,可以使用timestamp类型,timestamp是date的扩展类型,能支持到毫秒,毫秒的显示精度是6位,不过有效位是3位,即最大值达到999,满1000ms就进为1s。而与to_date()对应的转换函数可以使用to_timestamp()。两个date相减得到是两个时间的间隔,单位是天,两个timestamp相减的话,不能直接的得到天数,而是得到多少天,多少小时,多少秒,多少毫秒等。
select (sysdate-to_date('2017-11-01 00:00:00','yyyy-mm-dd hh24:mi:ss')) date相减 from dual;
输出是: 804.753923611111
select (systimestamp-to_timestamp('2017-11-01 00:00:00','yyyy-mm-dd hh24:mi:ss')) timestamp相减 from dual;
输出是:+000000804 18:05:39.344376000
时间差,转换 xx天xx时xx分xx秒 如下:
select
extract (day from dt2 - dt1) ||'天'||
extract (hour from dt2 - dt1) ||'小时'||
extract (minute from dt2 - dt1) ||'分钟'||
extract (second from dt2 - dt1) ||'秒' as 时间差
from
( select to_timestamp ('2020-01-05 15:51:50','yyyy-mm-dd hh24:mi:ss') dt1,
to_timestamp ('2020-01-14 17:30:30','yyyy-mm-dd hh24:mi:ss') dt2
from dual
)
输出结果: 9天1小时38分钟40秒
也可以使用with temp as
with t as (
select to_timestamp('2020-01-05 15:51:50','yyyy-mm-dd hh24:mi:ss')
-to_timestamp('2020-01-14 17:30:30','yyyy-mm-dd hh24:mi:ss') as datec
from dual
)
select extract(day from datec)||'天'
||extract(hour from datec)||'小时'
||extract(minute from datec)||'分钟'
||extract(second from datec)||'秒' as 时间差
from t;
输出结果: -9天-1小时-38分钟-40秒