Question:
Need assistance in converting seconds, stored in a variable, into a human-readable format comprising days, hours, minutes, and seconds.
Example:
Given $uptime = 1640467 seconds, the expected result would be:
18 days 23 hours 41 minutes
Solution:
To achieve this conversion, we can utilize the DateTime class. Here's a custom function that employs it:
function secondsToTime($seconds) { $dtF = new \DateTime('@0'); // Create a DateTime object for the day 0 $dtT = new \DateTime("@$seconds"); // Create a DateTime object for the specified seconds return $dtF->diff($dtT)->format('%a days, %h hours, %i minutes and %s seconds'); }
Usage:
Simply call the secondsToTime function with the number of seconds as the argument. For example:
echo secondsToTime(1640467); # Output: 18 days, 23 hours, 41 minutes and 7 seconds
For demonstration, please refer to the following code:
<kbd> $uptime = 1640467; echo secondsToTime($uptime); </kbd>
The above is the detailed content of How Can I Convert Seconds to a Human-Readable Time Format (Days, Hours, Minutes, Seconds)?. For more information, please follow other related articles on the PHP Chinese website!