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
Release: 2024-12-07 11:23:15
Original
860 people have browsed it

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
Copy after login

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');
}
Copy after login

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
Copy after login

For demonstration, please refer to the following code:

<kbd>
$uptime = 1640467;
echo secondsToTime($uptime);
</kbd>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template