tags:

views:

99

answers:

3
+3  Q: 

PHP - Compare Date

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?

+3  A: 
strtotime($var);

Turns it into a time value

time() - strtotime($var);

Gives you the seconds since $var

if((time()-(60*60*24)) < strtotime($var))

Will check if $var has been within the last day.

Chacha102
thanks, so much!
alexus
+1  A: 

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());
}
Alix Axel
Why the weird backwards logic and extraneous booleans? Why not just "return strtotime($time) == strtotime('today')", "return strtotime($time) > time()", and "return strtotime($time) < time()"?
Bobby Jack
@Bobby Jack: I had more functionality in those functions, forgot to delete the extra code. Fixed now.
Alix Axel
A: 

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

if (date1 > date2)

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.

Bobby Jack