How to Use the Oracle TRUNC Function With Dates
TRUNC isn't just for numbers in Oracle DB, it can also be used for dates. See how you can call up your dates and format them just how you want.
Join the DZone community and get the full member experience.
Join For FreeThe Oracle TRUNC function can be used with both numbers and dates. In this article, I'll explain how it can be used with date values.
TRUNC Syntax for Dates
If you want to use the TRUNC function for dates, the syntax is:
TRUNC (datevalue, format)
The parameters are:
- datevalue (mandatory): This is the date value that is to be truncated.
- format (optional): This is the format that the datevalue parameter will be truncated to.
Data Types
You can supply several different date data types as part of the TRUNC function.
You can specify a DATE value. Or, you can specify a TIMESTAMP value.
When you truncate the value using this TRUNC function, the value returned is a DATE data type. This is always the case, even if you provide a TIMESTAMP data type.
Formats for Truncating
The second parameter in the TRUNC function is the format parameter. This determines what the specified date is truncated to.
For example, if you specify a date of 3-FEB-2017, and a format of "YEAR", then the returned value will be 1-JAN-2017. It will be truncated to the beginning of that year.
If you use the same date but specify a value of "MONTH", it will get truncated to 01-FEB-2017.
A similar approach is taken with date values that contain time.
Let's take a look at some examples.
Examples
This example uses TRUNC on a date value with no time. I've used the TO_DATE function here.
SELECT TRUNC(TO_DATE('03-FEB-2017'), 'YEAR')
FROM dual;
Result
01/JAN/17
This example uses TRUNC but finds the first day of the week.
SELECT TRUNC(TO_DATE('03-FEB-2017'), 'D')
FROM dual;
Result
30/JAN/17
This example uses TRUNC after providing a date and time value, and truncates it to the hour.
SELECT TO_CHAR(TRUNC(TO_DATE('03-FEB-2017 10:45:12 AM', 'DD-MON-YYYY HH:MI:SS AM'), 'HH'), 'DD-MON-YYYY HH:MI:SS AM')
FROM dual;
Result
03-FEB-2017 10:00:00 AM
We need to use the TO_CHAR function to be able to see the time part of the output, because the default output is only day, month, and year.
This example uses TRUNC after providing the same date and time value, but truncates it to the minute.
SELECT TO_CHAR(TRUNC(TO_DATE('03-FEB-2017 10:45:12 AM', 'DD-MON-YYYY HH:MI:SS AM'), 'HH'), 'DD-MON-YYYY HH:MI:SS AM')
FROM dual;
Result
03-FEB-2017 10:45:00 AM
So, there's how you use the TRUNC function with a date value. It's a handy function and can be nested within other functions to format values to the output you want.
Opinions expressed by DZone contributors are their own.
Comments