-12

I have a Two variable with value date type assigned to it. Now I want to find difference of those two variable values.

$d1='2016-08-24 12:22:13';
$d2='2016-08-24 12:22:30';

difference of d2-d1 is 17 seconds. How to find it in php?

Bibek Shakya
  • 1,233
  • 2
  • 23
  • 45
Jay Doshi
  • 666
  • 1
  • 5
  • 16

3 Answers3

4
// Instantiate a DateTime 
$datetimefirst = new DateTime('2016-08-24 12:20:00');
$datetimesecond = new DateTime('2016-08-24 12:34:00');
//calculate the difference
$difference = $datetimefirst->diff($datetimesecond);
//format the Output 
echo $difference->format('%Y-%m-%d %H:%i:%s');

reference

The DateTime class:
This class behaves the same as DateTimeImmutable except objects are modified itself when modification methods such as DateTime::modify() are called.

lejlun
  • 4,140
  • 2
  • 15
  • 31
  • 1
    Welcome to Stack Overflow! While this code snippet may solve the question, including an [explanation](http://meta.stackexchange.com/q/114762/305455) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, as this reduces the readability of both the code and the explanations! – jmattheis Aug 24 '16 at 08:27
  • i have added comment as well as reference ,and its working in PHP Version 5.5.11 – Shailendra Vasave Aug 24 '16 at 10:31
0

Here is the solution,

<?php

$d1='2016-08-24 12:22:13';
$d2='2016-08-24 12:22:30';
$diff=strtotime($d2)-strtotime($d1);
echo $diff;

?>
Jay Doshi
  • 666
  • 1
  • 5
  • 16
0

For get difference between two date you have to convert it into time stamp first and take difference from there.

$d1='2016-08-24 12:22:13';
$d2='2016-08-24 12:22:30';
$diff=abs(strtotime($d2)-strtotime($d1));

echo "Diff ".date('H',$diff)." hours ".date('i',$diff)." minutes ".date('s',$diff)." Seconds";

here I have used abs() for convert into positive value of difference.

Haresh Vidja
  • 8,340
  • 3
  • 25
  • 42