How to subtract 2 dates in oracle to get the result in hour and minute

后端 未结 8 1905
深忆病人
深忆病人 2020-12-16 20:49

I want to subtract 2 dates and represent the result in hour and minute in one decimal figure.

I have the following table and I am doing it in this way but the result

8条回答
  •  感动是毒
    2020-12-16 21:12

    This is a very ugly way to do it, and this first part doesn't exactly question by the OP, but it gives a way to get results by subtracting 2 date fields -- in my case, the CREATED_DATE and today represented by SYSDATE:

    SELECT FLOOR(ABS(MONTHS_BETWEEN(CREATED_DATE, SYSDATE)) / 12) || ' years, '  
    || (FLOOR(ABS(MONTHS_BETWEEN(CREATED_DATE, SYSDATE))) - 
       (FLOOR(ABS(MONTHS_BETWEEN(CREATED_DATE, SYSDATE)) / 12)) * 12) || ' months, '  
    -- we take total days - years(as days) - months(as days) to get remaining days
    || FLOOR((SYSDATE - CREATED_DATE) -      -- total days
       (FLOOR((SYSDATE - CREATED_DATE)/365)*12)*(365/12) -      -- years, as days
       -- this is total months - years (as months), to get number of months, 
       -- then multiplied by 30.416667 to get months as days (and remove it from total days)
       FLOOR(FLOOR(((SYSDATE - CREATED_DATE)/365)*12 - (FLOOR((SYSDATE - CREATED_DATE)/365)*12)) * (365/12)))  
    || ' days, '   
    -- Here, we can just get the remainder decimal from total days minus 
    -- floored total days and multiply by 24       
    || FLOOR(
         ((SYSDATE - CREATED_DATE)-(FLOOR(SYSDATE - CREATED_DATE)))*24
       )
    || ' hours, ' 
    -- Minutes just use the unfloored hours equation minus floored hours, 
    -- then multiply by 60
    || ROUND(
           (
             (
               ((SYSDATE - CREATED_DATE)-(FLOOR(SYSDATE - CREATED_DATE)))*24
             ) - 
             FLOOR((((SYSDATE - CREATED_DATE)-(FLOOR(SYSDATE - CREATED_DATE)))*24))
           )*60
        )
    || ' minutes'  
    AS AGE FROM MyTable`
    

    It delivers the output as x years, x months, x days, x hours, x minutes. It could be reformatted however you like by changing the concatenated strings.

    To more directly answer the question, I've gone ahead and written out how to get the total hours with minutes as hours.minutes:

    select  
    ((FLOOR(end_date - start_date))*24)
    || '.' ||
    ROUND(
           (
             (
               ((end_date - start_date)-(FLOOR(end_date - start_date)))*24
             ) - 
             FLOOR((((end_date - start_date)-(FLOOR(end_date - start_date)))*24))
           )*60
        )
    from 
    come_leav;   
    

提交回复
热议问题