So, PHP apparently feels like being a moron today. Or maybe it’s me. Or both.
function before($test,$bar) {
$test = date_create($test);
$bar = date_create($bar);
$diff = date_diff($bar,$test);
$diff = $diff->format('%r%a') * 1;
return $diff<0;
}
It refuses to accept that a date generated by the following means:
date('m-d-Y', strtotime($date));
…is anything but a BOOLEAN! If I output the result, it comes out as a string, but – with PHP pining to confound me – before() treats it like something that it isn’t. There is NOTHING here that should convert it to a boolean. I can feed it a string directly, and it works fine. Give it a date from a piece of code specifically made for the very purpose, well, we can’t have that ’cause…
Warning: date_diff() expects parameter ... to be DateTime, boolean given
I thought, “fine, I’ll give you your parser’s desire.”
function before($test,$bar) {
$test = new DateTime(date('Y-m-d',strtotime($test)));
$bar = new DateTime(date('Y-m-d',strtotime($bar)));
$diff = $bar->diff($test);
$diff = $diff->format('%r%a') * 1;
return $diff<0;
}
No change in result whatsoever. I gave it what it wanted, or at least what it said it wanted (I think), and it still rejects me. Coding mimicking reality.
I’m not terribly comfortable with dates yet. I’m also not terribly comfortable yet with how PHP handles the time of year. Any advice? And maybe how to get this to work, too?
Edit
Running var_dump($test)
object(DateTime)#7 (3) {
["date"]=>
string(19) "1970-01-01 00:00:00"
["timezone_type"]=>
int(3)
["timezone"]=>
string(13) "Europe/Berlin"
}
As explained in the manual, date_create() is an alias for DateTime::__construct(). And there we can read:
So it’s pretty clear where the boolean comes from.
Now, your code shows many conversions from Unix timestamp to string and viceversa but not the value you start from, so it’s impossible to point out the exact source of the problem. But I’d say you have certain confusion about the data types involved in date handling. Here’s a little summary:
Unix timestamp: it’s an integer that counts the number of seconds since the Unix Epoch (Jan 1970). It’s the value handled by legacy date functions that receive an integer as argument or return one.
DateTime: it’s the new object-oriented date feature introduced in PHP/5.2.
Strings: it’s not a standardised format per-se so it should only be used for display purposes or as intermediate format (for instance, to insert a date into a database).
Sadly, the DateTime constructor only accepts strings and does not even allow to tell the exact format (IMHO, a not well-thought design decision). To reduce the potential ambiguity (is
10/11/201110th Nov. or 11 Oct?), I suggest you use the"YYYY-MM-DD"format.A tip: decide whether to use timestamps or DateTime objects and stick to that. It’ll make your live easier.