Reputation: 801
Can I compare two dates in a string like numbers? Or should I retype them to ints?
Is this code ok?
<?php
$date1 = "20130102";
$date2 = "20151012";
if ($date1 < $date2){
echo "date1 < date2";
} elseif ($date1 > $date2){
echo "date1 > date2";
} else {
echo "date1 = date2";
}
?>
Upvotes: 0
Views: 765
Reputation: 2429
Your code is safe and correct under the following condition: Iff your dates are formatted like Ymd (according to php's date function)
The reason this works is that in all character sets that I can imagine the characters 0-9 sort exactly like the numbers 0-9 do. If you then use leading 0s your strings sort just like numbers.
N.B. that using strings as a data type for dates is a code smell. See this page (no.7)
Upvotes: 3