PHP检查日期是否过期,给定特定格式的日期

55

我有一个 PHP 事件日历,它通过查询数据库来获取日期。

我使用以下代码显示事件日期:

$event['date']

并且显示的格式为:

2013-07-31,例如。

现在,我需要做的是检查这个日期是否是过去的日期。

我该如何做呢?

5个回答

125

你可以使用 PHP 的 DateTime 类来比较日期:

$date = new DateTime($event['date']);
$now = new DateTime();

if($date < $now) {
    echo 'date is in the past';
}

注意:使用DateTime类优于strtotime(),因为后者只适用于2038年之前的日期。了解有关2038年问题的更多信息。



6
我强烈建议使用$date = DateTime::createFromFormat('Y-m-d', '2013-07-31');。 OP的示例是ISO8601格式,因此DateTime类有很大可能每次都“正确地解析”,但是对于不同的DateTime格式,为了确保转换过程中没有隐藏的错误,最好指定你要实例化的日期格式。 - Wes
1
@Wes 我喜欢你的方法 =) - Pierre
3
请注意,如果$event['date']是今天的日期(没有时间),这将被认为是“过去时”。要比较没有时间的日期,您可以执行$now = new DateTime(date('Y-m-d')); - But those new buttons though..

27
你可以使用 strtotime()time()
if (strtotime($event['date']) < time()) {
    // past date
}

这应该是最简单的方法。 - Rashod Chamikara Bandara

12

@Satch3000 您已将错误的答案(@Amal Murali)作为正确解决方案接受

请查看输出结果,在此我输入了今天的日期,但它返回的是以前的日期。

<?php

/* Enter today date */
$date = new DateTime("09/14/2017");
$now = new DateTime();

print_r($date);

print_r($now);


if($date < $now) {
    echo 'date is in the past';
}

结果将会是:

DateTime Object
(
    [date] => 2017-09-14 00:00:00.000000
    [timezone_type] => 3
    [timezone] => UTC
)
DateTime Object
(
    [date] => 2017-09-14 07:12:52.000000
    [timezone_type] => 3
    [timezone] => UTC
)
date is in the past

解决方案

$Date1 = strtotime(date('Y-m-d', strtotime('2017-09-15') ) ).' ';
$Date2 = strtotime(date('Y-m-d'));

  if($Date1 < $Date2) {
        echo 'date is in the past';
    }

2
但是... 2017-09-14 00:00:00.000000 在 2017-09-14 07:12:52.000000 之前。 - Charles Wood

4
if (time() > strtotime($event['date']))
{
    // current date is greater than 2013-07-31 
}

strtotime 函数使用这些规则解析日期字符串。


0
我只需要这种简单的方式。
<?php
  if(date('Y-m-d') == '2023-09-30'){
    die('in');
 } 
?>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接