How To Get Time Difference In Minutes In PHP ?

Dec 14, 2021

.

Admin

How To Get Time Difference In Minutes In PHP ?

Hi Friends,

This example is how to get time difference in minutes in php?

This example, 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.

So let's start following example.

Syntax:


date_diff($datetime1, $datetime2);

Parameters : The date_diff() function accepts two parameters as mentioned above and described below.

Example 1:

The below program illustrates the date_diff() function to get the time difference in minutes.

<?php

// PHP Program to illustrate

//date_diff() function

// Creating DateTime Objects

$dateTimeObject1 = date_create('2019-05-18');

$dateTimeObject2 = date_create('2020-05-18');

// Calculating the difference between DateTime Objects

$interval = date_diff($dateTimeObject1, $dateTimeObject2);

echo ("Difference in days is: ");

// Printing the result in days format

echo $interval->format('%R%a days');

echo "\n <br/>";

$min = $interval->days * 24 * 60;

$min += $interval->h * 60;

$min += $interval->i;

// Printing the Result in Minutes format.

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 Program to illustrate

// date_diff() function

// Creating DateTime Objects

$dateTimeObject1 = date_create('2020-05-14');

$dateTimeObject2 = date_create('2021-02-14');

// Calculating the difference between DateTime Objects

$interval = date_diff($dateTimeObject1, $dateTimeObject2);

echo ("Difference in days is: ");

// Printing the result in days format

echo $interval->format('%R%a days');

echo "\n <br/>";

$min = $interval->days * 24 * 60;

$min += $interval->h * 60;

$min += $interval->i;

// Printing the Result in Minutes format.

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 program to illustrate

// date_diff() function

// Creating DateTime objects

$dateTimeObject1 = date_create('19:15:00');

$dateTimeObject2 = date_create('12:15:00');

// Calculating the difference between DateTime objects

$interval = date_diff($dateTimeObject1, $dateTimeObject2);

// Printing result in hours

echo ("Difference in hours is:");

echo $interval->h;

echo "\n <br/>";

$minutes = $interval->days * 24 * 60;

$minutes += $interval->h * 60;

$minutes += $interval->i;

//Printing result in minutes

echo("Difference in minutes is:");

echo $minutes.' minutes';

?>

Output:

Difference in hours is:7

Difference in minutes is:420 minutes

#PHP