简体   繁体   中英

Comparing two timestamps in php

SO the scene is, I have a store which opens at 1:00am at night, and closes at 10:00pm. For any current time i just want to check whether that timestamp lies between store open and close times.

Yeap that's very simple, and still I don't know why, am finding it difficult. below is a piece of epic shit i am trying.

<?php

$t=time();  //for current time
$o = date("Y-m-d ",$t)."01:00:00"; //store open at this time
$c = date("Y-m-d ",$t)."22:00:00"; //store closes at this time

//Yes, its crazy .. but I love echoing variables 
echo "current time = ".$t;
echo PHP_EOL;
echo "Start = ".strtotime($o);
echo PHP_EOL;
echo "End = ".strtotime($c);
echo PHP_EOL;

// below condition runs well, $t is always greater than $o
if($t>$o){
  echo "Open_c1";
}else{
  echo "Close_c1";
}

//Here's where my variable $t, behaves like a little terrorist and proclaims itself greater than $c
if($t<$c){
    echo "Open_c2";
}else{
    echo "Close_c2";
}
?>

OUTPUT: on phpfiddle

current time = 1472765602 Start = 1472706000 End = 1472781600 Open_c1 Close_c2

Just one help, why ( $t < $c ) condition is false. Am I missing something very common or making a serious blunder.

Thank you.

That's because $o and $c are string and $t is time(); You need to change your ifs to

 if ($t < strtotime($c))

and

 if ($t > strtotime($o))

for it to work properly.

Try this instead

$o = date("Y-m-d 01:00:00"); //store open at this time
$c = date("Y-m-d 22:00:00"); //store closes at this time

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM