How to compare date in php – compare two dates – date with now time – much more

Cases: how to compare date in php, php compare datetime, php compare date with current date, php compare date with current date, php compare date with current date, how to compare two dates in php mysql, php mysql date comparison.

PHP compare date in php cases detail

PHP compare two dates condition. Dates can be user input in valid format or it can be from database date field value.

Here we assume date is below format.

YYYY-mm-dd H:i:s
e.g., 2017-09-14 08:30:55

compare date in php

PHP have many ways to compare two dates and get result, either first date is greater than or less than from second date.

I alway using below simple date compare condition and hope you also like to use it.

Condition for compare date in php

It’s simple condition which uses PHP strtotime() and time() functions.

strtotime(): Parse about any English textual datetime description into a Unix timestamp.
time(): Return current Unix timestamp.

Date compare between two PHP date variable


$date1 = '2017-09-14 00:00:01';
$date2 = '2017-09-14 00:00:02';

// check date1 is greater than date2
if ( strtotime($date1) > strtotime($date1) ) {
    //true
} else {
    //false
}

PHP compare user input date with current date


$userDate = '2017-09-14 00:00:01';

// check userDate is greater than current datetime
if ( strtotime($userDate) > time() ) {
    //true
} else {
    //false
}

PHP compare database date field value with current date


$dbDate = '2017-09-14 00:00:01';

// check dbDate is greater than current datetime
if ( strtotime($dbDate) > time() ) {
    //true
} else {
    //false
}

PHP compare user input date with database field date value


$userDate = '2017-09-14 00:00:01';
$dbDate = '2017-09-14 00:00:02';

// check userDate is greater than dbDate field value
if ( strtotime($userDate) > strtotime($dbDate) ) {
    //true
} else {
    //false
}