free stats

How to get time difference in minutes in PHP

Last Update : 13 Dec, 2022 How to Guide in PHP

In this article, you will learn the best two ways to get the time difference in minutes in PHP.

PHP provides two methods for getting the time difference in minutes.

 

01) Using strtotime() function.

Here, You can use the PHP strtotime() function to get the time difference between two dates in minutes.

<?php

	$dateTime1 = '2022-12-11 10:30:15';
	$dateTime2 = '2022-12-14 13:45:30';
		
	$fromTime = strtotime($dateTime1);
	$toTime = strtotime($dateTime2);
	$minutes_difference = round(abs($fromTime - $toTime) / 60,2). " min";

	echo $minutes_difference;
	
?>

This program produces the following result -:

4515.25 min

 

2) Using DateTime class.

To calculate the difference between two date times, you can use the PHP DateTime class also. 

The diff() method of the DateTime class returns a DateInterval object that calculates the time difference between two date/time objects.

Here, you can get total days, years, months, days, hours, minutes, seconds, etc.

<?php
	
	$dateTime1 = '2022-12-11 10:30:15';
	$dateTime2 = '2022-12-14 13:45:30'; 
	 
	$startDateTime = new DateTime($dateTime1); 
	$difference = $startDateTime->diff(new DateTime($dateTime2)); 
	 
	echo $difference->days.' Days<br>'; 
	echo $difference->y.' Years<br>'; 
	echo $difference->m.' Months<br>'; 
	echo $difference->d.' Days<br>'; 
	echo $difference->h.' Hours<br>'; 
	echo $difference->i.' Minutes<br>'; 
	echo $difference->s.' Seconds<br>';


	// Get the time difference in minutes
	$totalMinutes = ($difference->days * 24 * 60); 
	$totalMinutes += ($difference->h * 60); 
	$totalMinutes += $difference->i; 
	 
	echo 'Time difference in minutes: '.$totalMinutes;

?>

This program produces the following result -:

3 Days
0 Years
0 Months
3 Days
3 Hours
15 Minutes
15 Seconds
Time difference in minutes: 4515

 

You found this tutorial / article valuable? Need to show your appreciation? Here are some options:

01. Spread the word! Use following buttons to share this tutorial / article link on your favorite social media sites.

02. Follow us on Twitter, GitHub ,and Facebook.