In many applications, we deal with time durations, especially when working with timestamps or recording the lengths of certain activities. Quite often, these durations are stored or manipulated in seconds. However, representing these durations in seconds isn’t very human-readable. In such cases, converting the duration to hours and minutes can be more meaningful to the end-users. This article will guide you through an easy-to-follow PHP function that converts a duration in seconds to a formatted string representing hours and minutes.

Time Formatting

In PHP, we have multiple ways to format time. PHP's date() function is commonly used to format timestamps. However, when it comes to representing a duration, especially in hours and minutes, a custom approach is required. This is where sprintf() comes in handy. The sprintf() function allows you to write a formatted string, which makes it ideal for this task.

Minutes to Hours and Minutes

One of the most straightforward techniques to convert minutes to hours and minutes in PHP involves using basic arithmetic operations. For instance, if you have a duration of 150 minutes, it can be converted to 2 hours and 30 minutes. This can be achieved by dividing the total minutes by 60 and using the floor function to get the hours. The remainder when divided by 60 gives the minutes.

Simple Conversion Technique

One of the most straightforward techniques to convert minutes to hours and minutes in PHP involves using basic arithmetic operations. For instance, if you have a duration of 150 minutes, it can be converted to 2 hours and 30 minutes. This can be achieved by dividing the total minutes by 60 and using the floor function to get the hours. The remainder when divided by 60 gives the minutes.

$totalMinutes = 150;
$hours = floor($totalMinutes / 60);
$minutes = $totalMinutes % 60;

echo "$totalMinutes minutes is equal to $hours hours and $minutes minutes.";

This code snippet will output: "150 minutes is equal to 2 hours and 30 minutes."

Using the DateTime Class

PHP's DateTime class offers a more sophisticated approach, especially when dealing with more complex time manipulations. You can use the DateInterval class along with DateTime to format the time span in hours and minutes. Here’s how you can achieve the conversion using the DateTime class:

$totalMinutes = 150;

// Create a DateInterval instance
$interval = new DateInterval('PT' . $totalMinutes . 'M');

// Format the interval in hours and minutes
$formattedInterval = $interval->format('%h hours and %i minutes');

echo "$totalMinutes minutes is equal to $formattedInterval.";

Seconds to Hours and Minutes

In most applications, time is typically stored in seconds (timestamps) for ease of computation. However, displaying time in seconds is not very intuitive for users. For instance, saying a video is 7200 seconds long is not as relatable as saying it is 2 hours long. This is where PHP can help in effectively making this conversion.

You can either modify the code we mentioned in the previous section, or define a convenient and useful function for use throughout the entire project.

Defining the Function

Converting a duration in seconds to a formatted string representing hours and minutes between two different time points is pretty straightforward.

Here is a simple code snippet that can help you achieve this, and output the customized string in the format you want.

Let's create a reusable function called getHoursMinutes. The function accepts two parameters - the duration in seconds and the format of the output string. It then calculates the hours and minutes from the seconds and returns a formatted string.

Function

/**
* Get hours and minuties formatted string.
*
* @param integer $seconds
* @param string  $format
*
* @return string
*/
function getHoursMinutes($seconds, $format = '%02d:%02d') {
    if (empty($seconds) || ! is_numeric($seconds)) {
        return false;
    }
    $minutes = round($seconds / 60);
    $hours = floor($minutes / 60);
    $remainMinutes = ($minutes % 60);
    return sprintf($format, $hours, $remainMinutes);
}

The function first checks if the provided seconds are valid. If not, it returns false. It then converts the seconds to minutes, rounds them up, and then calculates the number of whole hours in those minutes. Any remaining minutes are computed using the modulo operation.

Finally, the function uses sprintf() to format the string as per the desired output.

Parameters

  • $seconds: This is the duration in seconds which you want to convert.
  • $format: This optional parameter lets you customize the format of the output string. The default format is HH:MM.

Usage

Let’s look at different examples showing how this function can be used:

Example 1: Using the default format.

echo getHoursMinutes(3800);

Result:

01:03

Example 2: Custom format with leading zeros.

echo getHoursMinutes(3800, '%02d hours %02d minutes');

Result:

01 hours 03 minutes

Example 3: Custom format without leading zeros.

echo getHoursMinutes(3800, '%d hours and %d minutes');

Result:

1 hours and 3 minutes

Example 4: Calculating duration between two time points.

$a = strtotime('2010-02-12 13:24');
$b = strtotime('2010-03-12 02:02');

echo getHoursMinutes($b - $a, '%d hours and %d minutes.');

Result:

660 hours and 38 minutes.

Conclusion

Converting seconds / minutes into a more human-readable format of hours and minutes is a common requirement in web development. PHP provides various methods to achieve this, including basic arithmetic operations or utilizing the powerful DateTime class. The choice between the methods depends on the specific needs of the project and the preference of the developer. Being proficient in both techniques ensures that as a PHP developer, you can effortlessly tackle any time-based conversion challenges.

By using this getHoursMinutes function, you can easily convert durations in seconds to a more readable format in PHP. This is particularly useful for presenting data.

Last modified: June 21, 2023

Author

Comments

Write a Reply or Comment

Your email address will not be published.