简体   繁体   English

HSQLDB(HyperSQL)-如何以毫秒精度将UNIX时间戳获取为数字

[英]HSQLDB (HyperSQL) - how to get UNIX timestamp as a number with ms precision

I'm trying to get a Java-style long timestamp, that is, UNIX timestamp with millisecond precision * 1000, which fits into a non-floating-point type ( BIGINT ). 我正在尝试获取Java样式的long戳,即UNIX时间戳,精度为毫秒* 1000,适合非浮点类型( BIGINT )。

I didn't find a way to get it straight from some function, like CURRENT_TIMESTAMP , unless I was okay with formatting like 20181010123059123. 我找不到从诸如CURRENT_TIMESTAMP类的某些函数直接获取它的方法,除非我对格式如20181010123059123没问题。

So I found that this would give me something that looks like a number: 因此,我发现这会给我一些类似于数字的内容:

(CURRENT_TIMESTAMP - TIMESTAMP '2018-01-01 00:00:00') SECOND TO SECOND
-- Gives: 23649115.452000

Note that I am substracting 2018-... since I only care about the delta, not the absolute date. 请注意,我要减去2018-...因为我只关心增量而不是绝对日期。

I am not sure if this is the simples way. 我不确定这是否是简单的方法。
Turns out the type of this is INTERVAL, so I need to convert: 原来这种类型是INTERVAL,所以我需要转换:

CAST(
    (CURRENT_TIMESTAMP - TIMESTAMP '2018-01-01 00:00:00') SECOND TO SECOND
    AS DECIMAL(15,3)
)
-- Gives 23649115.000

Now the issue is, the precision is lost. 现在的问题是,精度丢失了。
So I wonder: Where is the .452 lost and how can I keep it? 所以我想知道: .452丢失了,我该如何保存? This is what the manual says : 这就是手册所说的

An interval value can be cast to a numeric type. 间隔值可以强制转换为数字类型。 In this case the interval value is first converted to a single-field INTERVAL type with the same field as the least significant filed of the interval value. 在这种情况下,首先将间隔值转换为单字段INTERVAL类型,其字段与间隔值的最低有效字段相同。 The value is then converted to the target type. 然后将该值转换为目标类型。 For example CAST (INTERVAL '1-11' YEAR TO MONTH AS INT) evaluates to INTERVAL '23' MONTH, and then 23. 例如,CAST(以INTVAL表示的年间隔为“ INTERVAL'1-11”,则为MONTVAL)将计算为INTERVAL'23'MONTH,然后为23。

And the ultimate question is: 最终的问题是:
How can I get UNIX timestamp-like number of milliseconds since some moment, eg UNIX epoch start? 从某个时刻(例如UNIX纪元开始)起,如何获得类似于UNIX时间戳的毫秒数?

My current whole SQL: 我目前的整个SQL:

SELECT  
(CURRENT_TIMESTAMP - TIMESTAMP '2018-01-01 00:00:00') SECOND TO SECOND,
FLOOR(
     CAST(
      (CURRENT_TIMESTAMP - TIMESTAMP '2018-01-01 00:00:00') SECOND TO SECOND
       AS DECIMAL(15,3)
     ) * 1000
) 
FROM (VALUES(0));
-- Gives: 23649115.452000 | 23649115000

Turns out there's UNIX_MILLIS which I overlooked (because the broken PDF format manual prevents proper searching). UNIX_MILLIS我忽略了UNIX_MILLIS (因为损坏的PDF格式手册阻止了正确的搜索)。

SELECT  UNIX_MILLIS() FROM (VALUES(0)) 

Which renders my attempts above a nice excercise in intervals. 这使我的尝试在间隔时间上表现得很好。

I still wonder, how should I CAST an interval to retain the milliseconds part. 我仍然不知道,我应该怎么CAST的间隔保留毫秒部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM