How to Get Time Difference in Minutes in PHP

Calculating the time difference between two dates or timestamps is a common task in PHP, especially when working with scheduling, event management, or tracking time intervals.

In this article, we'll explore how to calculate the time difference in minutes using PHP.

To calculate the time difference in minutes, you can follow these steps:

  1. Convert the two dates or timestamps to DateTime objects.
  2. Calculate the difference between the two DateTime objects.
  3. Extract the minutes from the difference.

Here's a step-by-step guide:

1. Convert Dates or Timestamps to "DateTime" Objects

You need to convert the given dates or timestamps to DateTime objects for further calculations. The DateTime class in PHP makes this conversion easy.

Here's an example of how to convert two timestamps to DateTime objects:

$timestamp1 = 1633113600; // First timestamp
$timestamp2 = 1633119000; // Second timestamp

$date1 = new DateTime("@$timestamp1");
$date2 = new DateTime("@$timestamp2");

In this example, we create DateTime objects from the Unix timestamps $timestamp1 and $timestamp2. The @ symbol is used to denote that the number is a timestamp.

2. Calculate the Time Difference

To calculate the time difference between the two DateTime objects, you can use the diff() method.

This method returns a DateInterval object, which represents the difference between two dates. Here's how to calculate the difference:

$interval = $date1->diff($date2);

3. Extract Minutes from the Difference

To get the time difference in minutes, you can extract the minutes component from the DateInterval object. Here's how to do it:

$minutesDifference = $interval->i;

In this code, we use the i property of the DateInterval object to obtain the minutes component of the difference.

Complete Example

Here's a complete example that calculates the time difference in minutes between two timestamps:

$timestamp1 = 1633113600; // First timestamp
$timestamp2 = 1633119000; // Second timestamp

$date1 = new DateTime("@$timestamp1");
$date2 = new DateTime("@$timestamp2");

$interval = $date1->diff($date2);

// print_r($interval);

$minutesDifference = $interval->days * 24 * 60;
$minutesDifference += $interval->h * 60;
$minutesDifference += $interval->i;

echo "Time Difference: $minutesDifference minutes";

Output:

Time Difference: 90 minutes

In this example, the code first converts the timestamps to DateTime objects, calculates the time difference, and finally extracts and displays the difference in minutes.


Conclusion

Calculating the time difference in minutes between two dates or timestamps is a useful task in many PHP applications. By using the DateTime class and the diff() method, you can easily obtain the time difference and work with it in your PHP code. This is particularly valuable for applications that involve scheduling, event management, and time tracking.