我想编写一个脚本,检查当前日期/时间是否已经超过了 2010年05月15日下午4点
我该如何使用 PHP 的 date() 函数来执行这个检查?
自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
}
传递给DateTime构造函数的字符串将根据这些规则进行解析。
请注意,也可以使用time
和strtotime
函数。 查看原回答。
此外还有DateTime类,它实现了比较运算符的函数。
// $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';
}
strtotime
函数,将您设置的日期/时间转换为时间戳:http://php.net/manual/en/function.strtotime.php。strtotime
不能正确处理您的日期/时间格式(例如,“下午4:00”可能有效但不是“在下午4点”),则需要使用字符串函数(例如substr
)解析/纠正格式,并通过另一个函数(例如mktime
)检索您的时间戳。if ($calulated_timestamp > time()) { /* date in the future */ }
),以确定设置的日期/时间是过去还是未来。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;
}
$myDate
等于string (0) ""
时,这肯定行不通。 - Nikola Petkanski
new DateTime('2010-05-15')
只是一个示例,可以是您之前初始化的任何DateTime对象。 - Salman A$object
是一个 DateTime 对象,我使用了if (new DateTime() > $object) {}
但是它的工作结果不正确。但是if (time() > $bject->getTimeStamp()) {}
的工作结果却是正确的。@Salman A - user4271704