Convert seconds to Hour:Minute:Second

前端 未结 27 2167
说谎
说谎 2020-11-22 07:56

I need to convert seconds to \"Hour:Minute:Second\".

For example: \"685\" converted to \"00:11:25\"

How can I achieve this?

27条回答
  •  花落未央
    2020-11-22 08:41

    Solution from: https://gist.github.com/SteveJobzniak/c91a8e2426bac5cb9b0cbc1bdbc45e4b

    Here is a very clean and short method!

    This code avoids as much as possible of the tedious function calls and piece-by-piece string-building, and the big and bulky functions people are making for this.

    It produces "1h05m00s" format and uses leading zeroes for minutes and seconds, as long as another non-zero time component precedes them.

    And it skips all empty leading components to avoid giving you useless info like "0h00m01s" (instead that will show up as "1s").

    Example results: "1s", "1m00s", "19m08s", "1h00m00s", "4h08m39s".

    $duration = 1; // values 0 and higher are supported!
    $converted = [
        'hours' => floor( $duration / 3600 ),
        'minutes' => floor( ( $duration / 60 ) % 60 ),
        'seconds' => ( $duration % 60 )
    ];
    $result = ltrim( sprintf( '%02dh%02dm%02ds', $converted['hours'], $converted['minutes'], $converted['seconds'] ), '0hm' );
    if( $result == 's' ) { $result = '0s'; }
    

    If you want to make the code even shorter (but less readable), you can avoid the $converted array and instead put the values directly in the sprintf() call, as follows:

    $duration = 1; // values 0 and higher are supported!
    $result = ltrim( sprintf( '%02dh%02dm%02ds', floor( $duration / 3600 ), floor( ( $duration / 60 ) % 60 ), ( $duration % 60 ) ), '0hm' );
    if( $result == 's' ) { $result = '0s'; }
    

    Duration must be 0 or higher in both of the code pieces above. Negative durations are not supported. But you can handle negative durations by using the following alternative code instead:

    $duration = -493; // negative values are supported!
    $wasNegative = FALSE;
    if( $duration < 0 ) { $wasNegative = TRUE; $duration = abs( $duration ); }
    $converted = [
        'hours' => floor( $duration / 3600 ),
        'minutes' => floor( ( $duration / 60 ) % 60 ),
        'seconds' => ( $duration % 60 )
    ];
    $result = ltrim( sprintf( '%02dh%02dm%02ds', $converted['hours'], $converted['minutes'], $converted['seconds'] ), '0hm' );
    if( $result == 's' ) { $result = '0s'; }
    if( $wasNegative ) { $result = "-{$result}"; }
    // $result is now "-8m13s"
    

提交回复
热议问题