Comparing two timestamps in php
Asked Answered
S

2

6

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.

Shemikashemite answered 1/9, 2016 at 21:39 Comment(1)
My bad.. i forgot to convert $o & $c to string and was comparing a date with string.Shemikashemite
B
6

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.

Bisque answered 1/9, 2016 at 21:43 Comment(1)
yeap i got that, That's a blunder from my side. Thank buddy.Shemikashemite
G
2

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
Gundry answered 1/9, 2016 at 21:42 Comment(2)
Thanks man, my bad.. i forgot to convert it to string and was comparing a date with string.Shemikashemite
To clarify for anybody reading this whom may not know, its comparing integer timestamp to a date string., the two will never be equal, so you convert the string to an integar and you can do arithmetic comparisons. Comparing strings may lead you into needing more complicated code when integer can be if ((x - y) >= z)Narcotize

© 2022 - 2024 — McMap. All rights reserved.