【问题标题】:Time zone conversion in SQL querySQL查询中的时区转换
【发布时间】:2014-05-20 22:43:29
【问题描述】:

我正在使用查询从存储为 GMT 的 Oracle DB 获取一些应用程序接收日期。现在我必须在检索时将其转换为东部标准/夏令时。 我为此使用以下查询:

   select to_char (new_time(application_recv_date,'gmt','est'), 'MON dd, YYYY') from application

它适用于标准时间。但是对于夏令时,我们需要根据时区信息将其转换为“edt”。我不太确定如何做到这一点。请帮帮我

【问题讨论】:

  • 这是什么数据库?并非所有使用 SQL 的数据库都支持相同的时区处理方式......请使用适当的信息更新您的标签 - oraclesql-servermysqlpostgres 或任何您正在使用的东西!
  • 抱歉错过了..现在更新(Oracle)

标签: sql oracle gmt timezone-offset


【解决方案1】:

您可以使用此查询,而不必担心时区更改。

select to_char(cast(application_recv_date as timestamp) at time zone 'US/Eastern',
               'MON dd, YYYY'
              )
from application;

例如:

美国东部时间:

select cast(date'2014-04-08' as timestamp) d1,
       cast(date'2014-04-08' as timestamp) at time zone 'US/Eastern' d2
from dual;

D1                                 D2
---------------------------------- -------------------------------------------
08-APR-14 12.00.00.000000 AM       07-APR-14 08.00.00.000000 PM US/EASTERN

美国东部标准时间:

select cast(date'2014-12-08' as timestamp) d1,
       cast(date'2014-12-08' as timestamp) at time zone 'US/Eastern' d2
from dual;

D1                                 D2
---------------------------------- -------------------------------------------
08-DEC-14 12.00.00.000000 AM       07-DEC-14 07.00.00.000000 PM US/EASTERN

更新:

感谢Alex Poole提醒,当不指定时区时,使用本地时区进行转换。

要强制将日期识别为 GMT,请使用 from_tz。

from_tz(cast(date'2014-12-08' as timestamp), 'GMT') at time zone 'US/Eastern'

【讨论】:

  • 我跟着你的步骤。但是,为什么我在下面的代码中得到不同的日期 d2 和 d3 select cast(date'2014-12-08' as timestamp) d1, new_time( cast(date'2014-12-08' as timestamp) ,'gmt','edt') d2, cast(date'2014-12-08' as timestamp) at time zone 'US/Eastern' d3 from dual D1 ==> 08-DEC-14 12.00.00.000000000 AM D2 ==> 07-DEC-2014 20:00:00 D3 ==> 14 年 12 月 7 日 01.30.00.000000000 PM 美国/东部
  • @satyanarayana - d2 正在从 GMT 转换为 EDT,这比 EatÂPeach 的示例晚了一个小时,因为它不应该在 12 月的夏令时 - 使用 EST 会起作用,但它更容易、更安全使用区域。 d3 正在从您的本地时区转换,而不是从 GMT 转换。
  • @Alex Poole - 非常感谢您让我知道我是从本地时区而不是 GMT 转换的。
  • @satyanarayana - 如果您的源数据真的是 GMT,而不是英国时间 (GMT/BST),那么您可以强制它被这样识别:select from_tz(cast(application_recv_date as timestamp), 'GMT') at time zone 'US/Eastern' from ...
【解决方案2】:

在 Oracle 中,您可以通过以下查询来实现:

Select current_timestamp, current_timestamp at time zone 'Australia/Sydney' from dual;

Australia/Sydney 是您要在其中转换时间的时区名称。

【讨论】:

    【解决方案3】:

    已经有一个函数可以将所需列的时间从一个时区转换为另一个时区:-

     convert_tz("columname or / the time you want to convert", fromTimeZone, ToTimeZone)
    

    例如:- 我想将 dateTIme 列的时间从印度时间 (IST) 转换为巴西时区,因为我的主机数据库时间默认在印度,它需要印度时间:-

    1. 印度时间为 GMT+5:30
    2. 巴西时间是 GMT-5:30

    convert_tz(dl.modified_datetime,'+5:30','-3:00') 'modified_time'

    所以,在这个过程中你可以很容易地转换它。

    【讨论】:

      猜你喜欢
      • 2012-05-08
      • 2014-09-18
      • 2020-12-21
      • 2012-09-06
      • 2021-12-31
      • 2013-09-17
      • 2011-11-30
      • 2021-08-13
      相关资源
      最近更新 更多