Oracle计算时间差为毫秒的实现代码

oracle 中我们知道用 to_date 函数可以进行秒、分、时、天、月、年、周等时间差的计算,但是毫秒却不好计算,to_date 函数只能精确到秒,毫秒则只能用 to_timestamp 函数,但是这个函数不像 to_date 这样直接减出来的差值就是 number 类型,如果用 to_number 函数转换也会报错。

这里我是用分隔字符串单独计算毫秒部分,如果有更好的办法,请大家分享一下,下面是查询时间差为毫秒的模板(字段1 – 字段2):

select 
(
 (
  (to_timestamp(字段1, 'yyyy-mm-dd hh24:mi:ss.ff9') + 0)
  -
  (to_timestamp(字段2, 'yyyy-mm-dd hh24:mi:ss.ff9') + 0)
 ) * 24 * 60 * 60
 +
 to_number
 (
  '0' ||
  (
    to_number(substr(字段1, instr(字段1, '.'))) 
    - 
    to_number(substr(字段2, instr(字段2, '.')))
  )
 )
) * 1000
from 表名

这里是相差的毫秒数,如果需要显示小数的秒请删除 “( ) * 1000”这部分,下面是个测试代码,直接运行:

select 
(
 (
  (to_timestamp('2016-04-13 17:13:50.998', 'yyyy-mm-dd hh24:mi:ss.ff9') + 0)
  -
  (to_timestamp('2016-04-13 17:13:47.235', 'yyyy-mm-dd hh24:mi:ss.ff9') + 0)
 ) * 24 * 60 * 60
 +
 to_number
 (
  '0' ||
  (
    to_number(substr('2016-04-13 17:13:50.998', instr('2016-04-13 17:13:50.998', '.'))) 
    - 
    to_number(substr('2016-04-13 17:13:47.235', instr('2016-04-13 17:13:50.235', '.')))
  )
 )
) * 1000
from dual

结果为:3763

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐