0

Hello i am learning php i tried to use the date function to display the current time. I have an if statement to check the current time whether it is greater than the next hour. Here is the code

<?
$current_time= date('G:i:s');
$next_time= date('G:i:s',strtotime('+1hour'));
if($current_time > $next_time )
{

    echo $current_time." is greater than ".$next_time;


}
?>

At the time of writing this code it was 9:23:39 and the next hour should have been 10:23:39

Surprisingly i got :

9:23:39 is greater than 10:23:39

Am i missing something here. Please help

1
  • 1
    you compare strings, not times Commented Aug 16, 2011 at 5:30

2 Answers 2

3

Keep in mind you are comparing strings, not numbers. 9 is greater than 1 and therefore returns true.

Either use the DateTime class to do this, or compare the unix timestamps (time() and strtotime('+1hour'))

Sign up to request clarification or add additional context in comments.

2 Comments

you mean something like this $next_time=time(strtotime('+1hour'));
strtotime returns a timestamp itself. Just store time() in a variable and strtotime('+1 hour') in another.
1

you could use a integer to work the if statement

$var = date("U",timestamp)

to get the number of Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) thus giving you a number which you can determine which one is greater.

2 Comments

i did something like this and it worked : $current_time= date("U"); $next_time=date("U",strtotime('+1hour'));
i normally configure my timestamps in other variables but you have a great idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.