【问题标题】:How to create an Oracle date based on separate date and time components?如何基于单独的日期和时间组件创建 Oracle 日期?
【发布时间】:2016-04-15 16:36:15
【问题描述】:

如何根据 DATE 列中的日期和固定字符串创建 Oracle DATE 变量?

即:使用to_date,日期来自mytable.date_col,字符串固定为“05:30”?

【问题讨论】:

  • 我在回答你的最后一个问题时使用了两种方法 *8-) 你所说的“变量”是什么意思 - 只是在查询中使用的生成值,还是 PL/SQL 变量?

标签: sql oracle date datetime


【解决方案1】:

您可以转换为字符串并返回,忽略任何现有的时间部分:

to_date(to_char(date_col, 'YYYY-MM-DD') || ' 05:30:00', 'YYYY-MM-DD HH24:MI:SS')

to_char() 仅将日期部分作为字符串获取,例如 '2015-04-15'。然后将您的固定时间附加到该字符串,因此它变为'2015-04-15 05:30:00'。然后使用合适的匹配格式模型将其转换为日期。

或者使用trunc() 将日期返回到午夜(假设它可能有更晚的时间)并添加代表该时间的一天的小数部分;这是 24 小时中的 5.5 小时,所以 5.5/24:

trunc(date_col) + 5.5/24

或相同的东西有一个间隔:

trunc(date_col) + interval '0 05:30:00' day to second

所有三个的快速演示:

with mytable (date_col) as (
  select to_date('2016-04-15 15:16:17', 'YYYY-MM-DD HH24:MI:SS') from dual
)
select to_date(to_char(date_col, 'YYYY-MM-DD') || ' 05:30:00',
    'YYYY-MM-DD HH24:MI:SS') as res1,
  trunc(date_col) + 5.5/24 as res2,
  trunc(date_col) + interval '0 05:30:00' day to second as res3
from mytable;

RES1                RES2                RES3              
------------------- ------------------- -------------------
2016-04-15 05:30:00 2016-04-15 05:30:00 2016-04-15 05:30:00

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-20
    • 2018-12-14
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多