Sunday, April 28, 2013

Oracle Dates

Internal Date Format
Oracle dates are stored as a structure made up of 7 fields each of which is 1 bytes long.
byte 1: century + 100
byte 2: year + 100
byte 3: month
byte 4: day of month
byte 5: hour + 1
byte 6: minute + 1
byte 7: second + 1
create table t (d date);

insert into t values (to_date('2001-05-30 08:05:30','yyyy-mm-dd hh24:mi:ss'));

select dump(d) from t;

DUMP(D)
--------------------------------------------------------------------------------
Typ=12 Len=7: 120,101,5,30,1,1,1
Default Date Format
The default date format is used whenever a date value has to be displayed (e.g. the result of a select). It is set using the nls_date_format initialization parameter. By default it is 'dd-MON-yy'. You can change this for the current session using the 'ALTER SESSION' command.
alter session set nls_date_format='yyyy-mm-dd hh24:mi:ss';
Adding days
Adding days is very simple - just use normal arithmetic operators (+ and -).
alter session set nls_date_format='yyyy-mm-dd';
var d varchar2(10);
exec :d := '2010-01-31';
select :d, to_date(:d)+1 from dual;

:D                               TO_DATE(:D
-------------------------------- ----------
2010-01-31                       2010-02-01
Adding months
Adding months is just as easy but you have to be aware of a little quirk. When adding a month to an end of month date, the result is also the end of month. Note that you can use negative numbers for the second argument.
Moving from a month with 30 days to a month with 31 days could "lose" a day.
exec :d := '2001-04-30';

select :d,add_months(:d,1) from dual;

:D                               ADD_MONTHS
-------------------------------- ----------
2001-04-30                       2001-05-31
This is what could happen when moving from a non-leap year to a leap year.
exec :d := '2003-02-28';

select :d,add_months(:d,12) from dual;

:D                               ADD_MONTHS
-------------------------------- ----------
2003-02-28                       2004-02-29

0 comments:

Post a Comment

Please Post your Comments..!