I have written a function to convert a date into a Unix time stamp. The function is written to work no matter what the current DST status is (e.g. EST or EDT). This is the function:
function unix_time_from_date(in_date in date) return number
as
ut number := 0;
tz varchar2(8) := '';
begin
-- Get the local timezone from the passed in date
-- Assuming the date supplied is for the local time zone
select
extract(
timezone_abbr from cast(in_date as timestamp with local time zone)
)
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;
This function works great when I execute it from a client like JDeveloper. From what I gather, this is because the client is supplying time zone information to the first query. However, if I use the function from within a procedure that is called from a mod_plsql page, then I get the error ORA-01857: not a valid time zone. This error is being thrown from the new_time function because tz is set to 'UNK'.
So, I implemented a work-around for this problem like so:
function unix_time_from_date(in_date in date) return number
as
ut number := 0;
tz varchar2(8) := '';
begin
-- Get the local timezone from the passed in date
-- Assuming the date supplied is for the local time zone
select
extract(
timezone_abbr from cast(in_date as timestamp with local time zone)
)
into tz
from dual;
if tz = 'UNK' then
select
extract(
timezone_abbr from cast(sysdate as timestamp with local time zone)
)
into tz
from dual;
end if;
-- 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;
Except, this still fails with tz being set to 'UNK'. Does anyone know what could be happening here? Why can’t I get the local time zone abbreviation when the function is called from a Oracle Application Server process?
The function as written does not work when the session calling it does not have the time zone information set. Therefore, you need to explicitly specify the source time zone. The following function solves this problem (and corrects the return type):
Note the addition of a second parameter to the function. This parameter,
in_src_tz, is used to indicate what time zone thein_dateparameter is in. The value ofin_src_tzshould be one of the timezone listed in thetznamecolumn of thev$timezone_namestable.Also, you cannot simply select the value of the
tzabbrevcolumn in thev$timezone_namestable due to time zone having multiple abbreviations. By using the extract, you will get the current abbreviation with DST factored in.