Reputation: 8287
All across my php code i'm storing dates and times in UTC, but i'm also using mysql to store datetimes (also in utc).
is there any way that date comparisons can fail with the greater than and less than operator?
$curdate=date('Y-m-d H:i:s');
if($start_datetime>$curdate)
Upvotes: 2
Views: 7115
Reputation: 11
is there any way that date comparisons can fail with the greater than and less than operator?
Not if you're sure the date string is properly formatted. But let's talk about that. I just mistakenly typed a five-digit year in a date INPUT element in Edge and it allowed it, sending the value "19920-01-01" to the server. A date like that compares as in the past to $curdate
when comparing as a string.
To make matters worse, the PHP DateTime class doesn't correctly parse a five digit year:
php > var_dump(new DateTime("19920-01-01 10:30:00"));
object(DateTime)#1 (3) {
["date"]=>
string(26) "2000-01-01 10:30:00.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(13) "Europe/Berlin"
}
So, you can't even rely on converting to DateTime and then doing your comparison. I now reject date strings coming from the browser that don't match the regular expression ^\d{4}-\d{2}-\d{2}$
. After that, I can then safely do a string comparison to $curdate
.
Upvotes: 0
Reputation: 54016
PHP:
change date into UNIX timestamp using strtotime()
and then u can compare.
MySQL:
change dataType of date column to DateTime
and then u can compare below way:
$d1 = new DateTime('2008-08-03 14:52:10');
$d2 = new DateTime('2008-01-03 11:11:10');
var_dump($d1 == $d2);
var_dump($d1 > $d2);
var_dump($d1 < $d2);
Upvotes: 3
Reputation: 157839
Nope.
There is no way for them to fail.
Mysql date format is intentionally made for this purpose.
There is not a single reason to convert it in whatever else format to compare.
Upvotes: 7
Reputation: 11215
strtotime($curdate) < strtotime($start_datetime)
strtotime() returns a int rperesenting the Seconds that passed since 01.01.1970 That means if $curdate date is "2011-01-01 12:00:00" and $start-datetime is "2011-01-01 12:00:01" then $start-datetime is bigger then $curdate because strtotime returns an integer for $start-datetime that is exactly one bigger than $curdate.
Upvotes: 0
Reputation: 18572
I prefer to compare the 'Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)'. Of course, this is only good for dates on/after 1970.
Given that $date1 and $date2 are two date variables to compare:
if (date("U",$date1) > date("U",$date2)) {
// $date1 is more recent than $date2
} else {
// $date1 is older than (or equal to) $date2
}
Upvotes: 0
Reputation: 5883
A direct datetime compare won't fail. You can do that.
A timestamp comparison would be faster, but I don't think such a micro-improvement in performance would be something to look for in a php application, plus you'll have to take into account the 2030 bug.
Upvotes: 0