1

i have this dates

$dt_occ     = mysql_result($info,0,"occ_data");
$dt_occ     = strtotime($dt_occ);
$dt_occ     = strtotime('+1 day' , $dt_occ);
$dt_unico   = date('d/m/Y H:i',$dt_occ);
$dt_il      = date('d/m/Y',$dt_occ);
$dt_alle    = date('H:i',$dt_occ);

I need to know how many hours remain between now and $dt_unico

fmineo
  • 804
  • 3
  • 11
  • 28
  • possible duplicate of [Calculate number of hours between 2 dates in PHP](http://stackoverflow.com/questions/3108591/calculate-number-of-hours-between-2-dates-in-php) – scrowler Nov 11 '13 at 21:18
  • What does var_dump($dt_occ) give after your first line of code? – vascowhite Nov 12 '13 at 06:27

3 Answers3

2

Take a look at the DateTime classes, they are much more flexible that strtotime() and date() (IMHO). Something like this will work for you:-

function getDiffInHours(\DateTime $earlierDate, \DateTime $laterDate)
{
    $utc = new \DateTimeZone('UTC');
    //Avoid side effects
    $first = clone $earlierDate;
    $second = clone $laterDate;
    //First convert to UTC to avoid missing hours due to DST etc
    $first->setTimezone($utc);
    $second->setTimezone($utc);
    $diff = $first->diff($second);
    return 24 * $diff->days + $diff->h;
}

Use it like this for example:-

$hours = getDiffInHours(new \DateTime($dt_occ), (new \DateTime($dt_occ))->modify('+ 1 day'));
var_dump($hours); //24
vascowhite
  • 18,120
  • 9
  • 61
  • 77
1

I think this will work for you.

$dt1 = new DateTime($dt_occ);
$dt2 = new DateTime($dt_occ);
$dt2->modify("+1 day");
$interval = $dt2->diff($dt1);
echo $interval->hours;

If you're using PHP5.5 you can simply this a little bit:

$dt1 = new DateTimeImmutable($dt_occ);
$dt2 = $dt1->modify("+1 day");
$interval = $dt2->diff($dt1);
echo $interval->hours;
John Conde
  • 217,595
  • 99
  • 455
  • 496
0

Since $dt_unico is derived from $dt_occ, which is a timestamp and time() gives the current time, also as a timestamp, subtracting the former from the latter will give the interval between them, in seconds.

Now, an hour is 60*60=3600 seconds, so:

$interval=(time()-$dt_occ)/3600;

Some notes, though:

  • I assumed that $dt_occ refers to the past. Future dates will give negative results, so if that's the case, switch the subtraction operands.

  • The above will give a floating point result. For an integral result, use the appropriate rounding function depending on the desired rounding method.

geomagas
  • 3,230
  • 1
  • 17
  • 27
  • If there is a DST change between the two times this will give an incorrect result by +/- 1 hour. – vascowhite Nov 12 '13 at 06:29
  • @vascowhite No it won't. `time()` will be converted to the correct timestamp, while `$dt_occ` is a timestamp already. – geomagas Nov 12 '13 at 08:31