问题
I have a few time fields that are INTERVAL DAY(0) TO SECOND(0) Datatypes to store various times of the day.
Currently on normal retrieval, my fields display as such:
+00 19:00:00.000000
How am I able to format this such that it displays as 19:00?
回答1:
You want hours and minutes from an interval. If that interval cannot exceed 24 hours, then you can add the interval to a date without time part and then use TO_CHAR
to get the formatted hours and minutes:
select to_char(trunc(sysdate) + myinterval, 'hh24:mi') from mytable
If, however, the interval can be larger (e.g. 100 hours and 15 minutes: 100:15), then you'll need another approach:
select
to_char(extract (day from myinterval) * 24 + extract (hour from myinterval)) ||
':' ||
to_char(extract (minute from myinterval), 'fm00')
from mytable
回答2:
In contradiction to documentation you cannot use function TO_CHAR()
for intervals. It allows to use INTERVAL values but the result is always the same. On another place the documentation says:
Interval data types do not have format models.
You can use either EXTRACT() function or you can work with Regular Expressions:
WITH t AS
(SELECT INTERVAL '19' HOUR + INTERVAL '30' MINUTE AS i FROM dual)
SELECT
LPAD(EXTRACT(HOUR FROM i), 2, '0')||':'||LPAD(EXTRACT(MINUTE FROM i), 2, '0'),
REGEXP_SUBSTR(i, '\d{2}:\d{2}')
FROM t;
Usually it is not very smart to use Regular Expression on date/time values. On the other hand, since format of INTERVAL
does not depend on any NLS-Settings it is a feasible option.
Disadvantage of EXTRACT
is when you have negative intervals. Such an interval would be written like -19:-30
because every component is returned with minus sign (-). Also be aware that EXTRACT
returns NUMBER
values, so you have to pad them with '0' manually.
回答3:
Use
substr(to_char(interval_value), 5, 5)
where interval_value
is the column name (incidentally, tables in a relational database don't have fields; they do have columns).
来源:https://stackoverflow.com/questions/45183024/formatting-interval-day0-to-second0