0

Hello I try to take the difference between two dates and display it.

My problem is that the time difference I get is not the correct one.

This is my code:

$time1 = strtotime('2014-03-28 15:20:00');
    $time2 = strtotime('2014-03-28 15:15:00');

    $diffTime = $time1 - $time2;

    echo date('H:i', $diffTime);

The result I get is:

02:05

The currect time should be this:

00:05

My guess that the date somehow takes timezone or something like this but Im not sure.

Thanks.

dasdasd
  • 1,971
  • 10
  • 45
  • 72
  • 1
    Recheck your result, [it works correctly](http://codepad.viper-7.com/KlEMif) – Hieu Le Mar 20 '14 at 07:26
  • 1
    Maybe use `gmdate()` instead of `date()` as per [this post](https://stackoverflow.com/questions/3172332/convert-seconds-to-hourminutesecond) – Fluff Mar 20 '14 at 07:28
  • go through this link i hope this will be help http://stackoverflow.com/questions/3763476/how-do-i-find-the-hour-difference-between-two-dates-in-php – Dexter Mar 20 '14 at 07:28
  • @HieuLe it works by chance in your example. it's not actually doing what the OP is intending – Andrew Brown Mar 20 '14 at 07:30

5 Answers5

2
/****************************************
$start_date = new DateTime('23:58:40'); *These two still give 
$end_date = new DateTime('00:00:00');   *a wrong answer
*****************************************/

$start_date = new DateTime('23:58:40');
$end_date = new DateTime('00:11:36');

$dd = date_diff($end_date, $start_date);

//Giving a wrong answer: Hours = 23, Minutes = 47, Seconds = 4 
echo "Hours = $dd->h, Minutes = $dd->i, Seconds = $dd->s";
ankit singh
  • 367
  • 1
  • 3
  • 13
1

So what you're actually doing here is generating two UNIX timestamps (numbers) and then subtracting them. then you're passing the resulting number as if it were still a timestamp to date().

essentially $diffTime is the number of seconds between your two times. you could divide by 60 to get minutes, and so on and so forth, but PHPs DateTime objects are much better.

Andrew Brown
  • 5,330
  • 3
  • 22
  • 39
0

From the PHP docs:

http://pl1.php.net/strtotime

Note: Using this function for mathematical operations is not advisable. It is better to use DateTime::add() and DateTime::sub() in PHP 5.3 and later, or DateTime::modify() in PHP 5.2.

D.R.
  • 20,268
  • 21
  • 102
  • 205
0

try this

<?php
$time1 = strtotime('2014-03-28 15:20:00');
$time2 = strtotime('2014-03-28 15:15:00');

echo round(abs($time1 - $time2) / 60,2). " minute"

    ?>
Abhishek
  • 517
  • 3
  • 18
0
Below is the solution of date time in years,days.hours,minutes and seconds.

$time1 = strtotime('2014-03-28 15:20:00');
$time2 = strtotime('2014-03-28 15:15:00');

$diffTime = $time1 - $time2;

$y = ($diffTime/(60*60*24*365));
$d = ($diffTime/(60*60*24))%365;
$h = ($diffTime/(60*60))%24;
$m = ($diffTime/60)%60;
$s = ($diffTime)%60;


echo "Minutes - " .$m;
echo "<br/>";
payal
  • 36
  • 2