Reputation: 2649
I'm trying to get today's date, and compare it to the date in my database, but the date in my database returns in a different form from the date that I get from the date function, so if I compare them in an if statement, the values are always going to be false. Is there a way for me to compare them so that it returns as true?
$date = date('y-m-d'); //date from date function ---> 15/07/19
$dateFromDatabase; //date from database ---> 2015/07/19
if ($date == $dateFromDatabase) {
echo "It's the same day.";
}
Upvotes: 1
Views: 285
Reputation: 909
strtotime
You have in php some great functions to convert your human readable dates to timestamps.
The first magic function is called strtotime (string to time) : give it your date, you get a UNIX timestamp! Let's see some examples:
echo strtotime('2008-04-12 13:24');
echo strtotime('12 april 2008 13:24');
echo strtotime('12.04.2008 13:24');
And more powerfull, strtotime can recognize some keywords:
echo strtotime('now');
echo strtotime('+4 days');
echo strtotime('+1 month');
echo strtotime('next monday');
echo strtotime('+2 weeks 3 days 4 hours 23 minutes');
The second argument of strtotime is a timestamp, and its default value is the actual timestamp (time()). So echo strtotime('+4 days') is relative to the current time. Of course you can also give strtotime your mysql date! (Note you can also use the mysql function UNIX_TIMESTAMP, which use a bit more ressources).
To compare dates, it's now just a detail:
// your first date coming from a mysql database (date fields)
$dateA = '2008-03-01 13:34';
// your second date coming from a mysql database (date fields)
$dateB = '2007-04-14 15:23';
if(strtotime($dateA) > strtotime($dateB)){
// bla bla
}
Better than substring, isn't it ?!
Here is just another example, not relative to current date but to a particular date:
strtotime('23 hours ago', strtotime('2005-04-13 14:00'));
This mean 23 hours ago relatively to the second given date, which must be a timestamp.
user manual doesn't give a complete description of the supported date formats. Strtotime('dd/mm/YYYY') doesn't work, it works only with mm/dd/YYYY format.
date in dd/mm/YYYY format, can be convert it to YYYY-mm-dd by using explode() function, but I think there are better solutions.
$date = '25/05/2010';
$date = str_replace('/', '-', $date);
echo date('Y-m-d', strtotime($date));
Upvotes: 3