How can I compare two dates in PHP?
In the database, the date looks like 2011-10-2.
If I wanted to compare today's date against the date in the database to see which one is greater, how would I do it?
I tried this,
$today = date("Y-m-d");
$expire = $row->expireDate //from db
if($today < $expireDate) { //do something; }
but it doesn't really work that way. What's another way of doing it?
Update: I know this post is kinda old but i just wanted to mention carbon, which is a class thats used with laravel but can be used with classic php and it does wonders with dates. check it out: Carbon
Simply you can check..
but both dates must be in same formatlike
etc.
I would'nt do this with PHP. A database should know, what day is today.( use MySQL->NOW() for example ), so it will be very easy to compare within the Query and return the result, without any problems depending on the used Date-Types
You can use simple PHP to compare dates:
This will give you true or false.
You can check the tutorials for more examples. Please click here.
first of all, try to give the format you want to the current date time of your server:
Obtain current date time
$current_date = getdate();
Separate date and time to manage them as you wish:
$current_date_only = $current_date[year].'-'.$current_date[mon].'-'.$current_date[mday]; $current_time_only = $current_date['hours'].':'.$current_date['minutes'].':'.$current_date['seconds'];
Compare it depending if you are using donly date or datetime in your DB:
$today = $current_date_only.' '.$current_time_only;
or
$today = $current_date_only;
if($today < $expireDate)
hope it helps
I had that problem too and I solve it by: