We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Useful Date and Time Functions in PL/SQL
Date and Time Function formats are different various database. we are going to discuss most common functions used in Oracle database. The function SYSDATE returns 7 bytes of data, which includes:
Century
Year
Month
Day
Hour
Minute
Second
1. Extract(): Oracle helps you to extract Year, Month and Day from a date using Extract() Function.
Explanation: Useful to retrieve only day from the System date/Current date or particular specified date.
2. ADD_MONTHS (date, n): Using this method in PL/SQL you can add as well as subtract number of months(n) to a date. Here ‘n’ can be both negative or positive.
Explanation: ADD_MONTHS function have two parameters one is date, where it could be any specified/particular date or System date as current date and second is ‘n’, it is an integer value could be positive or negative to get upcoming date or previous date.
3. LAST_DAY(date): Using this method in PL/SQL you can get the last day in the month of specified date.
Explanation: In above example, we are getting current date using SYSDATE function and last date of the month would be retrieved using LAST_DAY function and this function be also helpful for retrieving the first day of the next month.
4. MONTHS_BETWEEN (date1, date2): Using this method in PL/SQL you can calculate the number of months between two entered dates date1 and date2. if date1 is later than date2 then the result would be positive and if date1 is earlier than date2 then result is negative. Note: If a fractional month is calculated, the MONTHS_BETWEEN function calculates the fraction based on a 31-day month.
Explanation: Here date1 and date2 are not on the same day of the month that’s why we are getting the value in fractions, as well as date1 is later than date2 so the resulting value is in integers. Entered date should be in particular date format, that is the reason of using TO_DATE function while comparison within MONTHS_BETWEEN function. Let’s select the number of months an employee has worked for the company.
5. NEXT_DAY(date, day_of_week): It will return the upcoming date of the first weekday that is later than the entered date.It has two parameters first date where, system date or specified date can be entered; second day of week which should be in character form.
Explanation: It will help to provide the next upcoming date corresponding to the day, return type is always DATE regardless of datatype date. The second parameter must be a day of the week either full name or abbreviated.