24 October 2023

This snippet takes a number of milliseconds and converts it into a time format displaying hours, minutes, and seconds. The result is a formatted time string in the "H:i:s" format. This way, if you provide a value in $milliseconds, the code will convert it into a human-readable time format and display it as a text string in the "H:i:s" format.

Source code viewer
  1. $milliseconds = 1234567;
  2.  
  3. // Convert milliseconds to seconds with PHP_ROUND_HALF_UP.
  4. $seconds = round($milliseconds / 1000, 0, PHP_ROUND_HALF_UP);
  5.  
  6. // Calculate hours, minutes, and seconds
  7. $hours = floor($seconds / 3600);
  8. $seconds %= 3600;
  9. $minutes = floor($seconds / 60);
  10. $seconds %= 60;
  11.  
  12. // Format the result in "H:i:s" format.
  13. $timeFormat = sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
  14.  
  15. echo $timeFormat;
  16. // Output: 00:20:35
Programming Language: PHP