I have a problem with comparing dates. I pull one date from a database through an API. These dates are stored in an array because one column contains multiple dates and I have to cycle through them to find the next upcoming date. The dates are in the format: 'dd/mm/yy'
$rawDate = $e->calendarsummary;
$filter = preg_replace("/[a-z]/","", $rawDate);
$createArray = explode(',', $filter);
$dates = array_filter(array_map('trim', $createArray));
foreach($dates as $d)
{
$dateTime = DateTime::createFromFormat('dmy', $d);
if($dateTime >= $now)
{
$finalDate = $dateTime;
$total = $finalDate->format('l j/m/y');
break;
}
}
If I place a var_export of $dateTime after $dateTime = DateTime::createFromFormat('dmy', $d);
it returns 'false'. So I'm guessing $dateTime is empty although my array $dates is filled correctly.
a var_export of $dates returns:
array ( 0 => '15/06/13', 1 => '16/06/13', )
and a var export of $now returns todays date: '16/06/13'
So I'm a bit stuck why my variable $DateTime remains empty?
EDIT: Apparantly the return of 'false' means it's an error, so something went wrong when formatting my dates from the array?
If the $dates
array contains elements such 15/06/13
so use just use wrong date format. E.g.:
$dateTime = DateTime::createFromFormat('d/m/y', $d);
$dateTime = DateTime::createFromFormat('d/m/y', $d);
not
$dateTime = DateTime::createFromFormat('dmy', $d);
Your dates are in format d/m/y
, not dmy
. Try the following instead:
$dateTime = DateTime::createFromFormat('d/m/y', $d);
When I do that, I get:
class DateTime#1 (3) { public $date => string(19) "2013-06-15 17:17:12" public $timezone_type => int(3) public $timezone => string(3) "UTC" }
... instead of bool(false)
.
you could use strtotime as a different method.
$now = date('d/m/y');
foreach($dates as $d)
{
if(strtotime($d) >= strtotime($now))
{
$finalDate = $dateTime;
$total = date('l j/m/y', strtotime($d));
break;
}
}