In this article, we will learn how to get time difference in minutes using PHP.
We will be using the built-in function date_diff() to get the time difference in minutes. For this, we will be needed a start date and end date to calculate their time difference in minutes using the date_diff() function.
Syntax:
date_diff($datetime1, $datetime2);
Parameters: The date_diff() function accepts two parameters as mentioned above and described below.
- $datetime1: This is a mandatory parameter as it specifies the start/first DateTime object.
- $datetime2: This is a mandatory parameter as it specifies the end/second DateTime object.
Return Value: This function returns the difference between the first DateTime object and the second DateTime object otherwise it returns false on failure.
Example 1: The below program illustrates the date_diff() function to get the time difference in minutes.
PHP
<?php
$dateTimeObject1 = date_create( '2019-05-18' );
$dateTimeObject2 = date_create( '2020-05-18' );
$interval = date_diff( $dateTimeObject1 , $dateTimeObject2 );
echo ( "Difference in days is: " );
echo $interval ->format( '%R%a days' );
echo "\n<br/>" ;
$min = $interval ->days * 24 * 60;
$min += $interval ->h * 60;
$min += $interval ->i;
echo ( "Difference in minutes is: " );
echo $min . ' minutes' ;
?>
|
Output:
Difference in days is: +366 days
Difference in minutes is: 527040 minutes
Example 2:
PHP
<?php
$dateTimeObject1 = date_create( '2020-05-14' );
$dateTimeObject2 = date_create( '2021-02-14' );
$interval = date_diff( $dateTimeObject1 , $dateTimeObject2 );
echo ( "Difference in days is: " );
echo $interval ->format( '%R%a days' );
echo "\n<br/>" ;
$min = $interval ->days * 24 * 60;
$min += $interval ->h * 60;
$min += $interval ->i;
echo ( "Difference in minutes is: " );
echo $min . ' minutes' ;
?>
|
Output:
Difference in days is: +276 days
Difference in minutes is: 397440 minutes
Example 3:
PHP
<?php
$dateTimeObject1 = date_create( '19:15:00' );
$dateTimeObject2 = date_create( '12:15:00' );
$interval = date_diff( $dateTimeObject1 , $dateTimeObject2 );
echo ( "Difference in hours is:" );
echo $interval ->h;
echo "\n<br/>" ;
$minutes = $interval ->days * 24 * 60;
$minutes += $interval ->h * 60;
$minutes += $interval ->i;
echo ( "Difference in minutes is:" );
echo $minutes . ' minutes' ;
?>
|
Output:
Difference in hours is:7
Difference in minutes is:420 minutes
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
26 May, 2021
Like Article
Save Article