Reputation: 51341
In a SQL-database I make some selects, that get an duration (as result of a subtraction between two dates) in seconds as an int. But I want to format this result in a human-readable form like 'hh:mm' or 'dd:hh'. Is that possible in SQL and how can I realize this?
Upvotes: 2
Views: 10861
Reputation: 6297
In Oracle SQL:
-- 86,400 seconds in a day
-- 3,600 seconds in an hour
-- 60 seconds in a minute
select duration, -- seconds
trunc((duration)/86400) || ':' || -- dd
trunc(mod(duration,86400)/3600) || ':' || -- hh
trunc(mod(mod(duration,86400),3600)/60) || ':' || -- mm
mod(mod(mod(duration,86400),3600),60) -- ss
as human_readable
from dual
;
Upvotes: 0
Reputation: 536775
There is no standard, though many DBMSs have their own custom syntax.
In general it is better to be doing formatting-for-human-readability work in your application's presentation layer rather than anywhere near the database.
Upvotes: 0
Reputation: 338416
Assuming you have seconds:
DECLARE @DurationSeconds INT
-- 25h 45m 14s
SET @DurationSeconds = (25 * 3600) + (45 * 60) + (14)
SELECT
@DurationSeconds,
@DurationSeconds / 3600 hours,
@DurationSeconds % 3600 / 60 minutes,
@DurationSeconds % (3600 / 60) seconds
I'll let the task of formatting that nicely to you. :-)
Upvotes: 2
Reputation: 34375
Every database does it differently. I use PostgreSQL and it does it like so:
select to_char(my_date - my_other_date, 'HH:MM:SS');
You'll have to consult the manual for the database you are using.
Upvotes: 2
Reputation:
In SQL 2005, You can use the following:
select convert(varchar(8), dateadd(second, [SecondsColumn], 0), 108)
Which first converts the seconds into a date after 1900-01-01, and then gets the hh:mm:ss part.
If the column is more than 24 hours, this will roll over, if you want days and then hours in that case just do something like:
case when SecondsColumn> (24*60*60)
then
cast(datepart(day,datediff(dd, 0, dateadd(second, SecondsColumn, 0))) as varchar(4))
+ 'd' + convert(varchar(2), dateadd(second, SecondsColumn, 0), 108)
else
convert(varchar(8), dateadd(second, SecondsColumn, 0), 108)
end
Upvotes: 5