TO_DATE returning different dates for different format masks?

52,031

Solution 1

you've just shot yourself in the foot. its called implicit datatype conversion.

there is no TO_DATE(date) (which is what you're asking for) , so oracle has converted your query to TO_DATE(TO_CHAR(sysdate), 'DD MONTH YYYY') where TO_CHAR(sysdate) will pick up the default NLS format mask. depending on your default mask (see NLS_SESSION_PARAMETERS), your 1st may have resolved to the year 0012 and the 2nd to the year 0018. so 0012 is less than 0018.

if you want to truncate the sysdate, then just do trunc(sysdate)

Solution 2

If you want to see the time part when selecting SYSDATE. You may set NLS_DATE_FORMAT before issuing a SELECT statement.

ALTER SESSION SET NLS_DATE_FORMAT = 'yyyy-mm-dd hh24:mi:ss';

In IDEs (Today, PLSQL Developer, SQL Developer etc.) NLS_DATE_FORMAT can be set permanently to be used by every select statement you execute. In that case you dont need to run ALTER SESSION command prior to SELECT.

Share:
52,031
Kanagavelu Sugumar
Author by

Kanagavelu Sugumar

love to be a problem solver & be a designer..

Updated on July 12, 2022

Comments

  • Kanagavelu Sugumar
    Kanagavelu Sugumar almost 2 years

    I am having query on the below sql. Please help me.

     select to_date(sysdate, 'DD MONTH YYYY') , to_date(sysdate, 'yyyy/mm/dd hh24:mi:ss')
     from dual where 
     to_date(sysdate, 'DD MONTH YYYY') < to_date(sysdate, 'yyyy/mm/dd');
    

    1) to_date(sysdate, 'DD MONTH YYYY') this will give Date object without time (may be time is 00:00).
    Am i correct ? If not how will i get only Date object without Time in it?
    2) From the above query It seems to_date(sysdate, 'yyyy/mm/dd') is greater than to_date(sysdate, 'DD MONTH YYYY'). Why ??



    Update


    1) My aim in the above URL is to find out to_date function will only return date (or along with time) though format 'DD MONTH YYYY' is not mentioning the time chars(hh:mm..) in it.
    2) From the response i got that to_date will return Date with time always though we didn't mention the time chars.
    3) Finally to get only DATE we should use trunc() / to_date(to_char(sysdate,'mm-dd-yyyy'),'mm-dd-yyyy')

    Check the below

    select to_char(trunc(sysdate), 'yyyy/mm/dd hh24:mi:ss'), 
    to_char(to_date(to_char(sysdate, 'yyyy-MM-dd'),'yyyy/mm/dd hh24:mi:ss'),'yyyy/mm/dd hh24:mi:ss') 
    from dual;
    

    -->hh24 :24 is important to get 00:00 format.