在PHP中比较用户给定的当前时间和结束时间

在PHP中比较用户给定的当前时间和结束时间,php,Php,我正在比较当前时间和给定时间,但得到的结果是错误的 <?php date_default_timezone_set('Asia/Kolkata'); //echo date("h:i a"); //echo $query2['endtime']; if(date("h:i a") > $query2['endtime']) { $date = new DateTime(date("Y-m-d")); $date->m

我正在比较当前时间和给定时间,但得到的结果是错误的

  <?php 
    date_default_timezone_set('Asia/Kolkata');
    //echo date("h:i a");
    //echo $query2['endtime'];
    if(date("h:i a") > $query2['endtime'])
    {
    $date = new DateTime(date("Y-m-d"));
    $date->modify('+1 day');
    echo $date->format('Y-m-d');
    echo '<input type="date" name="date" id="date" min="'.$date->format('Y-m-d').'">';
    }
    else
    {
    echo '<input type="date" name="date" id="date" min="'.date("Y-m-d").'">';
    }

    ?>

您应该在任何地方使用时间戳,但在向用户显示时,由于时间戳在形式上的一致性,并且可以在任何地方移动

我建议您将dave times作为
“插入xx个值(etc、UNIX\u TIMESTAMP()等)”

然后在php中使用
time()
比较结果。您还可以使用date()将其转换为可呈现的格式

更新:

假设您现在有
$query2['endtime']
作为时间戳,只需这样做

if(time()>$query2['endtime']){
    //true
}


 //and to show to user
 echo date('Y-m-d', $query2['endtime']);
由于date()函数将为您提供日期字符串,因此您无法检查该字符串上的“>”操作。首先需要使用strotime()将日期字符串转换为时间戳,然后进行比较。下面的代码可能对您有所帮助

<?php 
date_default_timezone_set('Asia/Kolkata');
echo date("h:i a");
$query2= '05:00 pm';
$query21 =strtotime($query2);
echo $query21;
if(strtotime(date("h:i a")) > $query21)
{
    echo "yes";
}
else
{
    echo "no";
}
?>  

鉴于您已经在使用DateTime类,您会发现比较它们非常简单。像这样:

<?php 

// Create the dtz object once, and save it for re-use
$dtz = new DateTimeZone ("Asia/Kolkata");

// With the first parameter set to null it'll use the current time as well.
// So I'm using "midnight" here to emulate the results of your old code.
$date = new DateTime ("midnight", $dtz);

// Now we can create a DateTime object for the user-supplied date.
$endDate = new DateTime ($query2['endtime'], $dtz);

// Since both are DateTime objects we can now compare them directly.
if ($date > $endDate)
{
    $date->modify ('+1 day');
    echo $date->format ('Y-m-d');
}

echo '<input type="date" name="date" id="date" min="'.$date->format("Y-m-d").'">';

您需要使用strotime()制作时间戳并检查您是否可以解释@AzeezKallayi。我添加了一个示例代码作为答案。请查看您的时间以何种格式存储在数据库中。该用户正在输入的是下午5:00。因此,我正在获取该格式。@Nasir.if(strotime(date(“h:ia”))>strotime($query2['endtime'])。它是否有效。这是因为我建议您在存储和比较日期时使用时间戳。请重新阅读我的回答(strotime(date(“h:ia”)>strotime($query2['endtime'])。它是否有效。是的。如果$query2['endtime']是这种格式:“05:00 pm”是的,它是从5:00 pm开始的。我强烈建议继续使用DateTime类,因为OP是从上开始的,而不是旧的日期操纵库。从长远来看,这会使事情变得更容易。非常感谢。@Christian,不客气。顺便说一句,刚才对代码做了一点小小的修改,以避免不必要地重复代码。这两条回音线基本相同,因为如果情况不属实,日期无论如何都是“今天”。请记住向上投票,并(如果可能)接受您问题的最佳答案。:)好的,非常感谢。