将timestamp数据类型转换为unix时间戳Oracle

dee*_*pti 11 oracle oracle10g unix-timestamp

我在数据库中有一个时间戳数据类型,格式为24-JuL-11 10.45.00.000000000 AM,并希望将其转换为unix时间戳,我该如何获得它?

Ben*_*Ben 22

这个问题几乎与Convert Unixtime到Datetime SQL(Oracle)相反

正如贾斯汀洞穴所说:

没有内置功能.但写一个相对容易.因为Unix时间戳是自1970年1月1日以来的秒数

由于彼此删除两个日期会导致它们之间的天数,您可以执行以下操作:

create or replace function date_to_unix_ts( PDate in date ) return number is

   l_unix_ts number;

begin

   l_unix_ts := ( PDate - date '1970-01-01' ) * 60 * 60 * 24;
   return l_unix_ts;

end;
Run Code Online (Sandbox Code Playgroud)

作为其在自1970年以来的分数的秒数是无关紧要的.您仍然可以使用时间戳数据类型调用它...

SQL> select date_to_unix_ts(systimestamp) from dual;

DATE_TO_UNIX_TS(SYSTIMESTAMP)
-----------------------------
                   1345801660
Run Code Online (Sandbox Code Playgroud)

在回复你的评论时,我很抱歉,但我没有看到这种行为:

SQL> with the_dates as (
  2    select to_date('08-mar-12 01:00:00 am', 'dd-mon-yy hh:mi:ss am') as dt
  3      from dual
  4     union all
  5    select to_date('08-mar-12', 'dd-mon-yy')
  6      from dual )
  7  select date_to_unix_ts(dt)
  8    from the_dates
  9         ;

DATE_TO_UNIX_TS(DT)
-------------------
         1331168400
         1331164800

SQL>
Run Code Online (Sandbox Code Playgroud)

有3,600秒的差异,即1小时.

  • 该函数不考虑您当前的时区。Unix 时间戳是自 1970 年 1 月 1 日 00:00:00 **UTC** 以来的秒数。仅当您的本地时区为 UTC 时,结果才正确。 (4认同)

Jam*_*ers 11

我意识到答案已被接受,但我认为应该明确该答案中的函数不考虑传入日期的时区偏移量.应在GMT(+0)计算正确的Unix时间戳.to_date除非另有说明,Oracle的函数假定传入日期在本地时区.夏令时是真实的,这个问题更加严重.我通过以下功能解决了这个问题:

create or replace
  function unix_time_from_date
      (
        in_date   in date,
        in_src_tz in varchar2 default 'America/New_York'
      )
    return integer
  as
    ut      integer       := 0;
    tz      varchar2(8)   := '';
    tz_date timestamp with time zone;
    tz_stmt varchar2(255);
  begin
    /**
     * This function is used to convert an Oracle DATE (local timezone) to a Unix timestamp (UTC).
     *
     * @author James Sumners
     * @date 01 February 2012
     *
     * @param in_date An Oracle DATE to convert. It is assumed that this date will be in the local timezone.
     * @param in_src_tz Indicates the time zone of the in_date parameter.
     *
     * @return integer
     */

    -- Get the current timezone abbreviation (stupid DST)
    tz_stmt := 'select systimestamp at time zone ''' || in_src_tz || ''' from dual';
    execute immediate tz_stmt into tz_date;
    select
      extract(timezone_abbr from tz_date)
    into tz
    from dual;

    -- Get the Unix timestamp
    select
      (new_time(in_date, tz, 'GMT') - to_date('01-JAN-1970', 'DD-MM-YYYY')) * (86400)
    into ut
    from dual;

    return ut;
end unix_time_from_date;
Run Code Online (Sandbox Code Playgroud)

我有一些伴侣功能,unix_time并且unix_time_to_date,可在http://jrfom.com/2012/02/10/oracle-and-unix-timestamps-revisited/.我无法相信Oracle在没有实现这些目标的情况下已经完成了11g.