fmineo
fmineo

Reputation: 824

count hours remain between 2 dates with php

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

Upvotes: 1

Views: 613

Answers (3)

vascowhite
vascowhite

Reputation: 18440

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

Upvotes: 2

geomagas
geomagas

Reputation: 3280

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.

Upvotes: 0

John Conde
John Conde

Reputation: 219794

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;

Upvotes: 1

Related Questions