Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 753
Sarge Avatar asked Sep 01 '16 21:09

Sarge


People also ask

How can I compare two dates in PHP?

Comparing two dates in PHP is simple when both the dates are in the same format but the problem arises when both dates are in a different format. Method 1: If the given dates are in the same format then use a simple comparison operator to compare the dates. echo "$date1 is older than $date2" ; ?>

How can I compare today's date with another date in PHP?

You can get more information like the exact time difference between two dates using the diff() method and the date_diff() function in PHP.

How do you check if a date is greater than another date in PHP?

php $date1 = "2010-01-15"; $date2 = "2020-12-14"; $timestamp1 = strtotime($date1); $timestamp2 = strtotime($date2); if ($timestamp1 > $timestamp2) echo "$date1 is greater than $date2"; else echo "$date1 is less than $date2"; ?> What is PHP and how can I learn it? How to echo an array in PHP?


1 Answers

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.

like image 147
Forbs Avatar answered Sep 30 '22 07:09

Forbs