如何检查当前日期/时间是否已经过了设定的日期/时间?

我正在尝试编写一个脚本,以检查当前的日期/时间是否超过了 05/15/2010 at 4PM

如何使用 PHP 的 date ()函数执行此检查?

240901 次浏览

检查 PHP 的 strtotime-函数,将设置的日期/时间转换为时间戳: http://php.net/manual/en/function.strtotime.php

如果 strtotime不能正确处理日期/时间格式(“下午4:00”可能会有效,但“下午4:00”不行) ,那么需要使用字符串函数,例如 substr来解析/修正格式,并通过另一个函数(例如 mktime)检索时间戳。

然后将生成的时间戳与当前日期/时间(if ($calulated_timestamp > time()) { /* date in the future */ })进行比较,以确定设置的日期/时间是过去的还是将来的。

我建议您阅读 PHP 的 date/time-function 文档,并在遇到困难时带着一些源代码回到这里。

因为 PHP > = 5.2.2,所以可以这样使用 DateTime类:

if (new DateTime() > new DateTime("2010-05-15 16:00:00")) {
# current time is greater than 2010-05-15 16:00:00
# in other words, 2010-05-15 16:00:00 has passed
}

传递给 日期时间构造函数的字符串被解析为 根据这些规则


注意,也可以使用 timestrtotime函数。

还有一个 日期时间类,它为比较运算符实现一个函数。

// $now = new DateTime();
$dtA = new DateTime('05/14/2010 3:00PM');
$dtB = new DateTime('05/14/2010 4:00PM');


if ( $dtA > $dtB ) {
echo 'dtA > dtB';
}
else {
echo 'dtA <= dtB';
}
date_default_timezone_set('Asia/Kolkata');


$curDateTime = date("Y-m-d H:i:s");
$myDate = date("Y-m-d H:i:s", strtotime("2018-06-26 16:15:33"));
if($myDate < $curDateTime){
echo "active";exit;
}else{
echo "inactive";exit;
}