Oracle Convert Seconds to Hours:Minutes:Seconds

前端 未结 14 1112
再見小時候
再見小時候 2020-12-08 06:01

I have a requirement to display user available time in Hours:Minutes:Seconds format from a given total number of seconds value. Appreciate if you know a ORACLE function to d

相关标签:
14条回答
  • 2020-12-08 06:35

    You should check out this site. The TO_TIMESTAMP section could be useful for you!

    Syntax:

    TO_TIMESTAMP ( string , [ format_mask ] [ 'nlsparam' ] )

    0 讨论(0)
  • 2020-12-08 06:37

    Unfortunately not... However, there's a simple trick if it's going to be less than 24 hours.

    Oracle assumes that a number added to a date is in days. Convert the number of seconds into days. Add the current day, then use the to_date function to take only the parts your interested in. Assuming you have x seconds:

    select to_char(sysdate + (x / ( 60 * 60 * 24 ) ), 'HH24:MI:SS')
      from dual
    

    This won't work if there's more than 24 hours, though you can remove the current data again and get the difference in days, hours, minutes and seconds.

    If you want something like: 51:10:05, i.e. 51 hours, 10 minutes and 5 seconds then you're going to have to use trunc.

    Once again assuming that you have x seconds...

    • The number of hours is trunc(x / 60 / 60)
    • The number of minutes is trunc((x - ( trunc(x / 60 / 60) * 60 * 60 )) / 60)
    • The number of seconds is therefore the x - hours * 60 * 60 - minutes * 60

    Leaving you with:

    with hrs as (
      select x, trunc(x / 60 / 60) as h
        from dual
             )
     , mins as (
      select x, h, trunc((x - h * 60 * 60) / 60) as m
        from hrs
             )
    select h, m, x - (h * 60 * 60) - (m * 60)
      from mins
    

    I've set up a SQL Fiddle to demonstrate.

    0 讨论(0)
提交回复
热议问题