How to Get Time Difference in Hours and Minutes in PHP

AuthorSumit Dey Sarkar

Pubish Date06 Feb 2024

categoryPHP

In this tutorial we will learn how to get time difference in hours and minutes in PHP.

How to Get Time Difference in Hours and Minutes in PHP

How to get time difference in hours and minutes in PHP

To get the time difference in hours and minutes in PHP, you can use the DateTime class.

Here's an example:

// Two datetime objects representing start and end times
$startTime = new DateTime('2024-02-04 10:00:00');
$endTime = new DateTime('2024-02-04 14:30:00');

// Calculate the difference
$difference = $startTime->diff($endTime);

// Get the hours and minutes
$hours = $difference->format('%h');
$minutes = $difference->format('%i');

// Display the result
echo "Time difference: $hours hours and $minutes minutes.";

In the above example:

  • DateTime objects are created for the start and end times.
  • The diff method is used to calculate the difference between the two datetime objects.
  • The format method is then used to extract the hours (%h) and minutes (%i) from the difference.
  • The result is then displayed in hours and minutes.

Adjust the start and end times in the DateTime objects according to your requirements.

Comments 0

Leave a comment