DB2两个日期之间的毫秒数

7xllpg7q  于 2023-03-29  发布在  DB2
关注(0)|答案(3)|浏览(327)

我有两个数据类型为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
63lcw9qa

63lcw9qa1#

有更准确的TIMESTAMPDIFF替代方案。

SELECT 
  TIMESTAMPDIFF(1, CHAR (endtime - starttime)) / 1000
    AS TSDIFF_ORIG
, (DAYS             (endtime) - DAYS             (starttime)) * BIGINT (86400000)
+ (MIDNIGHT_SECONDS (endtime) - MIDNIGHT_SECONDS (starttime)) * 1000
+ (MICROSECOND      (endtime) - MICROSECOND      (starttime)) / 1000
    AS TSDIFF_REAL
FROM (VALUES (CURRENT TIMESTAMP, CURRENT TIMESTAMP + 35 MINUTE + 1.001 SECOND)) T (starttime, endtime)
TSDIFF_ORIGTSDIFF_真实的
二一零一二一零一
35g0bw71

35g0bw712#

TIMESTAMPDIFF返回整数,因此它可以返回的最大值为2 147 483 647
所以正如documentation所说
微秒(持续时间的绝对值必须小于3547.483648)
当TIMESTAMPDIFF必须返回微秒数时,到时间戳之间的最大持续时间为35分47秒483647微秒

c8ib6hqw

c8ib6hqw3#

开始和结束之间的时间戳差是多少?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对一个月的天数等做了一些假设
解决这个问题的经典方法是将时间戳转换为自某个开始时间(比如epoch)以来的毫秒数,然后减去它们。
像这样的函数(未经彻底测试)可能会有所帮助:

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) @

相关问题