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

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

Susan Sarandon
Release: 2024-12-11 15:15:10
Original
823 people have browsed it

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

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

Within this function:

  1. We create two DateTime objects: $dtF represents the starting point (0 seconds) and $dtT represents the target time (the provided seconds).
  2. We obtain the time difference between $dtT and $dtF using the diff() method.
  3. Finally, we format the difference into a human-readable string using the format() method.

To use the function, simply pass the seconds value as an argument:

echo secondsToTime(1640467);
Copy after login

This will output the desired result:

18 days, 23 hours, 41 minutes and 7 seconds
Copy after login

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!

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