Home >Backend Development >PHP Tutorial >How Can I Convert Seconds to a Human-Readable Time Format (Days, Hours, Minutes, Seconds)?

How Can I Convert Seconds to a Human-Readable Time Format (Days, Hours, Minutes, Seconds)?

Linda Hamilton
Linda HamiltonOriginal
2024-12-07 11:23:15887browse

How Can I Convert Seconds to a Human-Readable Time Format (Days, Hours, Minutes, Seconds)?

Converting Time from Seconds to Human-Readable Format

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn