我有两个数据类型为 timestamp(10) 的日期。现在我想计算这两个日期之间的毫秒数。
SELECT TO_CHAR(TIMESTAMPDIFF(1,CHAR(endtime- starttime))) AS "ms"
FROM TABLE
我得到当前错误:
[Code: -183, SQL State: 22008] A datetime arithmetic operation or a datetime scalar function has a result that is not within the va`lid range of dates.. SQLCODE=-183, SQLSTATE=22008, DRIVER=4.28.11
TIMESTAMPDIFF 返回一个 INTEGER,所以它可以返回的最大值是 2 147 483 647
正如文档所说
微秒(持续时间的绝对值必须小于 3547.483648)
当 TIMESTAMPDIFF 必须返回微秒数时,时间戳之间的最大持续时间为 35 分 47 秒 483647 微秒
开始和结束的时间戳有什么区别? TIMESTAMPDIFF 的范围相当有限。 FWIW,1 是微秒,最大间隔似乎是 35 分钟左右:
db2 "with t(starttime,endtime) as (values (current_timestamp, current_timestamp + 35 minute)) select TIMESTAMPDIFF(1,CHAR(endtime - starttime)) from t"
1
-----------
2100000000
1 record(s) selected.
db2 "with t(starttime,endtime) as (values (current_timestamp, current_timestamp + 36 minute)) select TIMESTAMPDIFF(1,CHAR(endtime - starttime)) from t"
1
-----------
SQL0183N A datetime arithmetic operation or a datetime scalar function has a
result that is not within the valid range of dates. SQLSTATE=22008
此外,请注意 TIMESTAMPDIFF 对一个月中的天数等做了一些假设
解决该问题的经典方法是将您的时间戳转换为自某个开始时间(例如纪元)以来的毫秒数,然后减去它们。
像这样的功能(未经过全面测试)可能会有所帮助:
create or replace function ms_since_epoch(ts timestamp)
returns bigint
return extract(epoch from ts)*1000
- extract(seconds from ts)::int
+ 1000*extract(milliseconds from ts) @