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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2832467/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:48:33  来源:igfitidea点击:

How can I check if the current date/time is past a set date/time?

phpdatedatetime

提问by dave

I'm trying to write a script that will check if the current date/time is past the 05/15/2010 at 4PM

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

How can I use PHP's date() function to perform this check?

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

回答by Salman A

Since PHP >= 5.2.2 you can use the DateTimeclass as such:

由于 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
}

The string passed to the DateTime constructoris parsed according to these rules.

根据这些规则解析传递给DateTime 构造函数的字符串。



Note that it is also possible to use timeand strtotimefunctions. See original answer.

请注意,也可以使用timestrtotime函数。请参阅原始答案

回答by VolkerK

There's also the DateTimeclass which implements a function for comparison operators.

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

回答by Select0r

Check PHP's strtotime-function to convert your set date/time to a timestamp: http://php.net/manual/en/function.strtotime.php

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

If strtotimecan't handle your date/time format correctly ("4:00PM" will probably work but not "at 4PM"), you'll need to use string-functions, e.g. substrto parse/correct your format and retrieve your timestamp through another function, e.g. mktime.

如果strtotime无法正确处理您的日期/时间格式(“4:00PM”可能会起作用,但不会“在 4PM”),您将需要使用字符串函数,例如substr解析/更正您的格式并通过以下方式检索您的时间戳另一个功能,例如mktime

Then compare the resulting timestamp with the current date/time (if ($calulated_timestamp > time()) { /* date in the future */ }) to see whether the set date/time is in the past or the future.

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

I suggest to read the PHP-doc on date/time-functions and get back here with some of your source-code once you get stuck.

我建议阅读有关日期/时间函数的 PHP 文档,并在遇到问题时返回此处提供一些源代码。

回答by Rakesh Kumar Pradhan

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