如何使用 SQL 显示两个不同区域的时间戳之间的实时差异?

How to show real time difference between timestamps in two different zones with SQL?

这个查询returns 0

SELECT (CURRENT_TIMESTAMP AT TIME ZONE 'PST' 
      - CURRENT_TIMESTAMP AT TIME ZONE 'UTC') AS td
  FROM dual

我怎样才能真正显示出真正的时间差异?例如,在这种情况下,我希望看到 -8 小时的差异。

在这个例子中,我使用了 CURRENT_TIMESTAMP,但我有一个真实的用例,我在两个不同的时区都有时间戳。我想要这两者之间的实时差异。

将值转换为不带时区的 TIMESTAMP

SELECT CAST(CURRENT_TIMESTAMP AT TIME ZONE 'PST' AS TIMESTAMP)
       - CAST(CURRENT_TIMESTAMP AT TIME ZONE 'UTC' AS TIMESTAMP)
       as td
FROM   DUAL;

输出:

TD
-000000000 08:00:00.000000

或者,考虑夏令时边界附近的时间:

-- Times around the DST boundary.
WITH times (t) AS (
  SELECT TIMESTAMP '2021-03-14 09:30:00 UTC' FROM DUAL UNION ALL
  SELECT TIMESTAMP '2021-03-14 10:30:00 UTC' FROM DUAL
)
SELECT t As t_utc,
       t AT TIME ZONE 'PST8PDT' AS t_pstpdt,
       (CAST(t AT TIME ZONE 'PST8PDT' AS TIMESTAMP)
        - CAST(t AT TIME ZONE 'UTC' AS TIMESTAMP)) AS td
FROM   times

输出:

T_UTC T_PSTPDT TD
2021-03-14 09:30:00.000000000 UTC 2021-03-14 01:30:00.000000000 PST8PDT -000000000 08:00:00.000000
2021-03-14 10:30:00.000000000 UTC 2021-03-14 03:30:00.000000000 PST8PDT -000000000 07:00:00.000000

db<>fiddle here

所以,您想找出时区之间的时差。 (这不是标题所说的;标题具有误导性。)

如果是这样,那么您不需要引用 current_timestamp 或任何类似的东西。

由于您是将 PST 与 UTC 进行比较,这与查找 PST 的 UTC 偏移量相同。这使问题变得更加容易。 (在一般情况下,您可以找到两个时区的偏移量并减去;在您的示例中,UTC 到自身的偏移量显然为零)。

select to_char(to_timestamp_tz('PST', 'tzr'), 'tzh:tzm') as pst_offset
from   dual;


PST_OFFSET
----------
-08:00