Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

"Stable" date component for TO_DATE(str, 'hh24:mi')?

mathguyJun 8 2017 — edited Jun 12 2017

Note: Originally I had TO_CHAR (instead of TO_DATE) in two places, pointed out by responders and now fixed here.

Suppose I want to convert a string STR with values like '06:00' (representing a time-of-day component in 'hh24:mi' format) into a number like 0.25 (representing the number of days since midnight, as in date arithmetic). Is it safe to calculate it as

to_date(STR, 'hh24:mi') - to_date('00:00', 'hh24:mi')

?

In a situation like above, TO_DATE attaches the first day of the current month as the "date" component to form a full date-time (the Oracle DATE data type). So this should be OK, except...  What if the query is run right at midnight at the beginning of a new month? Is it possible that one call to TO_DATE will pick up a different month than the other call to TO_DATE? Or is this behavior of TO_DATE based on a fixed date (or timestamp) that is used throughout the execution of the entire query? My suspicion is that it is, in fact, possible that the two calls to TO_DATE would pick up different months, if the conditions are "just right" for that to happen. So this approach would NOT be safe.

Please do not suggest "other ways to do it"   since that is not what I am asking.  Of course, there are other, safe ways to get the desired result; for example I can pre-concatenate a fixed string, like '2000-01-01', before applying TO_DATE, and change the format model accordingly. I could also convert directly from string to number using only string manipulations and elementary operations; I prefer not to, because that won't catch bad data such as '24:15' or '10:75', but all of this is off-topic to the question in this thread. I am simply asking if THIS approach is safe or if it should not be used, for the reason I explained.

Thank you!     -    mathguy

This post has been answered by Anton Scheffer on Jun 9 2017
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jul 10 2017
Added on Jun 8 2017
40 comments
3,062 views