简体   繁体   中英

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

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?

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 .

You can use strtotime() and time() :

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

strtotime parses the date sting using these rules .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM