«Back to Home

Oracle Jump Start

Topics

How To Use Date Functions in Oracle

Date Functions
 
All date functions returns a value of date data type except months_between, which returns a numeric value.
  • SYSDATE
  • ADD_MONTHS(d, n)
  • ROUND(d, [format])
  • TRUNC(d, [format])
  • MONTHS_BETWEEN(d1, d2)
  • LAST_DAY(d)
  • NEXT_DAY(date, day)
  • TO_CHAR(d, f)
  • TO_DATE(char, ‘f’)
SYSDATE
 
SYSDATE returns the current date and time of type DATE.
 
Example
  1. Select SYSDATE  
  2. from dual;  
1
ADD_MONTH(d, n)
 
This functions returns a date. It adds or subtracts month to or from a date.
 
Example
  1. Select Emp_Hiredate, ADD_MONTHS(Emp_hiredate, 4),  
  2. ADD_MONTHS(Emp_hiredate, -4) from employee  
  3. where Dept_no= 102;  
2
ROUND(d, [format])
 
This function round off the dates d to the unit, specified by format.
 
Example
  1. select ROUND(TO_DATE('17-june-07'), 'MM')"Nearest Month"  
  2. from dual;  
3

TRUNC(d, [format])
 
This functions returns the date d, truncated to the unit, specified by format.
 
Example
  1. Select TRUNC (TO_DATE('17-june-07 12:11:01','DD-MON-YY HH24:MI:SS'), 'year')  
  2. "first day"  
  3. from dual;  
4

MONTHS_BETWEEN(d1, d2)
 
This function returns the number of months between two dates, d1 and d2.
 
Example
 
  1. select MONTHS_BETWEEN('17-may-06''01-sep-08'),  
  2. MONTHS_BETWEEN('18-march-06','17-june-07')  
  3. from dual;  


LAST_DAY(d)
 
The function returns the date of the last day of the specified month.
 
Example
 
  1. Select SYSDATE, LAST_DAY(SYSDATE)   
  2. From dual;  
6
 
NEXT_DAY(date, day)
 
This function returns the date of the next specified day of the week after the date.
 
Example
  1. Select SYSDATE, NEXT_DAY(SYSDATE, ‘MONDAY’)  
  2. from dual;  
7

TO_CHAR(d, f)
 
This function converts the date ‘d’ to character format ‘f’.
 
Example
  1. Select SYSDATE, TO_CHAR(SYSDATE, ‘DAY’)  
  2. From Dual;  
8

TO_DATE(char, ‘f’)
 
This functions converts the character string representing date into a date format, according to specified ‘f’ format.
 
Example
  1. Select TO_CHAR(TO_DATE(’17-may-06’), ‘MM’)  
  2. from dual;  
9

Summary
 
Thus we learnt, date functions returns a value of date. Data type except months_between returns a numeric value and we learnt, how to use the date functions in Oracle with an example.