Reham Fahmy
Reham Fahmy

Reputation: 5073

conditional time compare

I'm using this within my sql code to record the time

`dt` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,

Output example : 2012-03-15 19:51:07

Question 1 what i want to do is to compare between time recoreded before and the time at certain moment.

$tr = "2012-03-15 19:51:07"; // time recorded

and

$tn = "2012-03-16 8:33:23"; // time now

so that i can say

if ($tn > $tr){
echo "something";
}else{
echo "something else";
}

Question 2 what if i wanna say if $tn > $tr by certain exact number of hours (example 3 hours) show something and else show something else. (conditional compare)

so can we really compare time ! ~thanks

Upvotes: 1

Views: 116

Answers (1)

Crashspeeder
Crashspeeder

Reputation: 4311

To compare the times you can use strtotime()

if (strtotime($tn) > strtotime($tr)) {
    echo "something";
} else {
    echo "something else";
}

strtotime() will give you the time in seconds. You could then subtract one from the other to get the number of seconds between the time recorded and the time now:

 $diff = strtotime($tn) - strtotime($tr);

Getting the number of hours is then just a matter of arithmetic.

$hours = floor($diff/3600);

Upvotes: 4

Related Questions