Convert Seconds into Human-Readable Days, Hours, Minutes, and Seconds
Converting seconds into its constituent time components can be a common task in programming. Let's tackle this challenge and achieve the desired outcome.
To convert the given seconds variable $uptime into days, hours, minutes, and seconds, we can leverage the DateTime class. This class provides an elegant way to manipulate and format dates and times.
Here's a straightforward function called secondsToTime() that accomplishes our goal:
function secondsToTime($seconds) { $dtF = new \DateTime('@0'); $dtT = new \DateTime("@$seconds"); return $dtF->diff($dtT)->format('%a days, %h hours, %i minutes and %s seconds'); }
Within this function:
To use the function, simply pass the seconds value as an argument:
echo secondsToTime(1640467);
This will output the desired result:
18 days, 23 hours, 41 minutes and 7 seconds
This approach provides a clean and efficient solution for converting seconds into its constituent time components, simplifying the task in various programming contexts.
The above is the detailed content of How Can I Convert Seconds into a Human-Readable Time Format (Days, Hours, Minutes, Seconds)?. For more information, please follow other related articles on the PHP Chinese website!