Tuesday, September 20, 2011

Converting ARS Timestamp to Date

There is one useful function on database level called "unixts_to_date" where you can convert your ARS or Unix timestamps to date. Here is the code for it:


CREATE OR REPLACE FUNCTION ARADMIN.unixts_to_date(unixts IN PLS_INTEGER) RETURN DATE IS

        /**
         * Converts a UNIX timestamp into an Oracle DATE
         */
        unix_epoch DATE := TO_DATE('19700101000000','YYYYMMDDHH24MISS');
        max_ts PLS_INTEGER := 2145916799; -- 2938-12-31 23:59:59
        min_ts PLS_INTEGER := -2114380800; -- 1903-01-01 00:00:00
        oracle_date DATE;
       
        BEGIN           
            IF unixts> max_ts THEN
                RAISE_APPLICATION_ERROR(
                    -20901,
                    'UNIX timestamp too large for 32 bit limit'
                );
            ELSIF unixts <min_ts THEN
                RAISE_APPLICATION_ERROR(
                    -20901,
                    'UNIX timestamp too small for 32 bit limit' );
            ELSE
                oracle_date := unix_epoch + NUMTODSINTERVAL(unixts, 'SECOND');
            END IF;           
            RETURN (oracle_date);
END;

The usage for this function is below:
select unixts_to_date(1316466000) from dual;

No comments:

Post a Comment