php 如何检查当前日期/时间是否超过设定的日期/时间?

cwxwcias  于 5个月前  发布在  PHP
关注(0)|答案(4)|浏览(63)

我试图写一个脚本,将检查当前日期/时间是否超过05/15/2010 at 4PM
如何使用PHP的date()函数来执行此检查?

rpppsulh

rpppsulh1#

你可以这样使用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

w8rqjzmb

w8rqjzmb2#

还有一个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';
}

字符串

owfi6suc

owfi6suc3#

检查PHP的strtotime-函数将您设置的日期/时间转换为时间戳:http://php.net/manual/en/function.strtotime.php
如果strtotime不能正确处理你的日期/时间格式(“4:00 PM”可能可以,但“at 4PM”不行),你需要使用字符串函数,例如substr来解析/纠正你的格式,并通过另一个函数检索你的时间戳,例如mktime
然后将结果时间戳与当前日期/时间(if ($calulated_timestamp > time()) { /* date in the future */ })进行比较,以查看设置的日期/时间是过去还是未来。
我建议阅读关于日期/时间函数的PHP-doc,一旦遇到问题,请带着一些源代码回到这里。

ykejflvf

ykejflvf4#

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

字符串

相关问题