Home » Php » PHP Check if date is past to a certain date given in a certain format

PHP Check if date is past to a certain date given in a certain format

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have a php event’s calender which queries the database to get the dates.

I display the event date using:

$event['date']

and this display’s in this format:

2013-07-31 for example.

Now, what I need to do is to check if this date is a past date to the current date.

How can I do this?

How to&Answers:

You can compare the dates with PHP’s DateTime class:

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

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

See it live!


Note: Using DateTime class is preferred over strtotime() since the latter will only work for dates before 2038. Read more about the Year_2038_problem.

Answer:

You can use strtotime() and time():

if (strtotime($event['date']) < time()) {
    // past date
}

Answer:

@Satch3000 You’ve accepted the wrong answer as a right solution ( @Amal Murali )

Please see the output, Here I input the today date but it returns current date as past date.

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

Output will be

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

Solution

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

Answer:

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

strtotime parses the date sting using these rules.