繁体   English   中英

比较php中的两个时间戳

[英]Comparing two timestamps in php

所以场景是,我有一家商店,晚上 1:00 开门,晚上 10:00 关门。 对于任何当前时间,我只想检查该时间戳是否位于商店开放时间和关闭时间之间。

是的,这很简单,但我仍然不知道为什么,我觉得很难。 下面是我正在尝试的一段史诗般的东西。

<?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";
}
?>

输出:在 phpfiddle

当前时间 = 1472765602 开始 = 1472706000 结束 = 1472781600 Open_c1 Close_c2

只是一个帮助,为什么 ( $t < $c ) 条件为假。 我是否遗漏了一些非常常见的东西或犯了严重的错误。

谢谢。

那是因为$o$c是字符串,而 $t 是 time(); 您需要将您的 ifs 更改为

 if ($t < strtotime($c))

 if ($t > strtotime($o))

使其正常工作。

试试这个

$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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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