[php] Compare given date with today

I have following

$var = "2010-01-21 00:00:00.0"

I'd like to compare this date against today's date (i.e. I'd like to know if this $var is before today or equals today or not)

What function would I need to use?

This question is related to php date datetime

The answer is


Here you go:

function isToday($time) // midnight second
{
    return (strtotime($time) === strtotime('today'));
}

isToday('2010-01-22 00:00:00.0'); // true

Also, some more helper functions:

function isPast($time)
{
    return (strtotime($time) < time());
}

function isFuture($time)
{
    return (strtotime($time) > time());
}

To complete BoBby Jack, the use of DateTime OBject, if you have php 5.2.2+ :

if(new DateTime() > new DateTime($var)){
    // $var is before today so use it

}

Expanding on Josua's answer from w3schools:

//create objects for the dates to compare
$date1=date_create($someDate);
$date2=date_create(date("Y-m-d"));
$diff=date_diff($date1,$date2);
//now convert the $diff object to type integer
$intDiff = $diff->format("%R%a");
$intDiff = intval($intDiff);
//now compare the two dates
if ($intDiff > 0)  {echo '$date1 is in the past';}
else {echo 'date1 is today or in the future';}

I hope this helps. My first post on stackoverflow!


$date1=date_create("2014-07-02");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);

(the w3schools example, it works perfect)


You can use the DateTime class:

$past   = new DateTime("2010-01-01 00:00:00");
$now    = new DateTime();
$future = new DateTime("2021-01-01 00:00:00");

Comparison operators work*:

var_dump($past   < $now);         // bool(true)
var_dump($future < $now);         // bool(false)

var_dump($now == $past);          // bool(false)
var_dump($now == new DateTime()); // bool(true)
var_dump($now == $future);        // bool(false)

var_dump($past   > $now);         // bool(false)
var_dump($future > $now);         // bool(true)

It is also possible to grab the timestamp values from DateTime objects and compare them:

var_dump($past  ->getTimestamp());                        // int(1262286000)
var_dump($now   ->getTimestamp());                        // int(1431686228)
var_dump($future->getTimestamp());                        // int(1577818800)
var_dump($past  ->getTimestamp() < $now->getTimestamp()); // bool(true)
var_dump($future->getTimestamp() > $now->getTimestamp()); // bool(true)

* Note that === returns false when comparing two different DateTime objects even when they represent the same date.


Some given answers don't have in consideration the current day!

Here it is my proposal.

$var = "2010-01-21 00:00:00.0"
$given_date = new \DateTime($var);

if ($given_date == new \DateTime('today')) {
  //today
}

if ($given_date < new \DateTime('today')) {
  //past
}

if ($given_date > new \DateTime('today')) {
  //future
}

One caution based on my experience, if your purpose only involves date then be careful to include the timestamp. For example, say today is "2016-11-09". Comparison involving timestamp will nullify the logic here. Example,

//  input
$var = "2016-11-09 00:00:00.0";

//  check if date is today or in the future
if ( time() <= strtotime($var) ) 
{
    //  This seems right, but if it's ONLY date you are after
    //  then the code might treat $var as past depending on
    //  the time.
}

The code above seems right, but if it's ONLY the date you want to compare, then, the above code is not the right logic. Why? Because, time() and strtotime() will provide include timestamp. That is, even though both dates fall on the same day, but difference in time will matter. Consider the example below:

//  plain date string
$input = "2016-11-09";

Because the input is plain date string, using strtotime() on $input will assume that it's the midnight of 2016-11-09. So, running time() anytime after midnight will always treat $input as past, even though they are on the same day.

To fix this, you can simply code, like this:

if (date("Y-m-d") <= $input)
{
    echo "Input date is equal to or greater than today.";
}

That format is perfectly appropriate for a standard string comparison e.g.

if ($date1 > $date2){
  //Action
}

To get today's date in that format, simply use: date("Y-m-d H:i:s").

So:

$today = date("Y-m-d H:i:s");
$date = "2010-01-21 00:00:00";

if ($date < $today) {}

That's the beauty of that format: it orders nicely. Of course, that may be less efficient, depending on your exact circumstances, but it might also be a whole lot more convenient and lead to more maintainable code - we'd need to know more to truly make that judgement call.

For the correct timezone, you can use, for example,

date_default_timezone_set('America/New_York');

Click here to refer to the available PHP Timezones.


Few years later, I second Bobby Jack's observation that last 24 hrs is not today!!! And I am surprised that the answer was so much upvoted...

To compare if a certain date is less, equal or greater than another, first you need to turn them "down" to beginning of the day. In other words, make sure that you're talking about same 00:00:00 time in both dates. This can be simply and elegantly done as:

strtotime("today") <=> strtotime($var)

if $var has the time part on 00:00:00 like the OP specified.

Replace <=> with whatever you need (or keep it like this in php 7)

Also, obviously, we're talking about same timezone for both. For list of supported TimeZones


Compare date time objects:

(I picked 10 days - Anything older than 10 days is "OLD", else "NEW")

$now   = new DateTime();
$diff=date_diff($yourdate,$now);
$diff_days = $diff->format("%a");
if($diff_days > 10){
    echo "OLD! " . $yourdate->format('m/d/Y');
}else{
    echo "NEW! " . $yourdate->format('m/d/Y');
}

$toBeComparedDate = '2014-08-12';
$today = (new DateTime())->format('Y-m-d'); //use format whatever you are using
$expiry = (new DateTime($toBeComparedDate))->format('Y-m-d');

var_dump(strtotime($today) > strtotime($expiry)); //false or true

If you do things with time and dates Carbon is you best friend;

Install the package then:

$theDay = Carbon::make("2010-01-21 00:00:00.0");

$theDay->isToday();
$theDay->isPast();
$theDay->isFuture();
if($theDay->lt(Carbon::today()) || $theDay->gt(Carbon::today()))

lt = less than, gt = greater than

As in the question:

$theDay->gt(Carbon::today()) ? true : false;

and much more;


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?