【发布时间】:2011-02-19 10:06:30
【问题描述】:
我正在尝试编写一个脚本来检查当前日期/时间是否超过05/15/2010 at 4PM
如何使用 PHP 的 date() 函数来执行此检查?
【问题讨论】:
我正在尝试编写一个脚本来检查当前日期/时间是否超过05/15/2010 at 4PM
如何使用 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 constructor 的字符串被解析为according to these rules。
请注意,也可以使用time 和strtotime 函数。 See original answer.
【讨论】:
new DateTime('2010-05-15') 只是一个示例,可以是您之前初始化的任何 DateTime 对象。
$object 是一个 DateTime 对象,我使用了 if (new DateTime() > $object) {} 并且它工作错误。但是if (time() > $bject->getTimeStamp()) {} 工作正常。 @萨尔曼A
还有一个 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';
}
【讨论】:
检查 PHP 的 strtotime-function 以将您设置的日期/时间转换为时间戳:http://php.net/manual/en/function.strtotime.php
如果strtotime 无法正确处理您的日期/时间格式(“4:00PM”可能有效但“下午 4 点”无效),您将需要使用字符串函数,例如substr 解析/更正您的格式并通过另一个函数检索您的时间戳,例如mktime.
然后将生成的时间戳与当前日期/时间 (if ($calulated_timestamp > time()) { /* date in the future */ }) 进行比较,以查看设置的日期/时间是过去还是未来。
我建议阅读有关日期/时间函数的 PHP 文档,一旦遇到困难,请返回此处获取一些源代码。
【讨论】:
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) ""。