I have been scouring stack and google to find a way to extract a date from timestamp w/o the trailing zero's still being a date and NOT a VARCHAR
variable
You cannot if you want the value to still be a DATE
A DATE
is stored internally as 7-bytes and always has year (2 bytes), month, day, hour, minute and second (1 byte each) components.
A TIMESTAMP
is stored internally with 11-20 bytes with the same year-to-second components as a DATE
but also fractional seconds components and optional time zone components.
Neither a DATE
nor a TIMESTAMP
has a format because they are just binary data and you cannot remove the time component because they both always have a time component.
SELECT TRUNC(to_date('2012-07-18 13:27:18', 'YYYY-MM-DD HH24:MI:SS')) FROM DUAL
gives: 18-JUL-12 00:00:00
The query outputs a DATE
and depending on the user interface that you use then the date may be implicitly cast to a string for outputting. SQL/Plus and SQL Developer use the NLS_DATE_FORMAT
session parameter to implicitly convert DATE
s to strings when it is displaying it to the user:
ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS';
SELECT TRUNC(to_date('2012-07-18 13:27:18', 'YYYY-MM-DD HH24:MI:SS')) FROM DUAL;
Outputs: 2012-07-18 13:27:18
ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD';
SELECT TRUNC(to_date('2012-07-18 13:27:18', 'YYYY-MM-DD HH24:MI:SS')) FROM DUAL;
Outputs: 2012-07-18
However, ANY user can change their own session parameters at ANY time so you should never rely on implicit formatting of dates.
If you want a DATE
then you should not expect it to be formatted in any particular way as it is just binary data. If you want a formatted date then you should explicitly convert it to a string with the formatting you require using TO_CHAR
:
SELECT TO_CHAR(
TRUNC( to_date('2012-07-18 13:27:18', 'YYYY-MM-DD HH24:MI:SS') ),
'DD/MM/YYYY'
)
FROM DUAL;
Outputs: 18/07/2012
db<>fiddle