I have run across php code the compares dates in YYYY-mm-dd format as strings. Does this work? It seems to work in simple cases, but I am not sure it makes sense to compare them as strings.
<?php
$today = '2013-02-11';
$start_date = '2013-02-11';
$end_date = '2013-02-12';
$on_promo = (($start_date <= $today) && ($end_date >= $today));
if ($on_promo)
{
echo 'ON promo';
}
else
{
echo 'OFF promo';
}
?>
When comparing strings in PHP using greater than or less than, it compares them in alphabetical order.
Alphabetically 2013-02-10
comes before 2013-02-13
If we have:
$date1 = '2013-02-10';
$date2 = '2013-02-13';
var_dump($date2 > $date1); // produces true
var_dump('apple' > 'banana'); // produces false
However, note that if the strings are both numerical, it will cast them both to integers
var_dump('11' > '101'); // produces false
var_dump('a11' > 'a101'); // produces true
var_dump('11a' > '101a'); // produces true
Therefore if using the format YYYY-MM-DD
you can compare two dates perfectly fine, however I really don't recommend relying on this. Someone might throw in a date like 2013-2-11
(note the month doesn't have the leading 0
) and it will completely throw off the logic. It is much better to take John Conde's suggestion and use DateTime
use strtotime
instead of comparing dates as strings
<?php
$today = date('U');
$start_date = strtotime('2013-02-11');
$end_date = strtotime('2013-02-12');
$on_promo = (($start_date <= $today) && ($end_date >= $today));
if ($on_promo)
{
echo 'ON promo';
}
else
{
echo 'OFF promo';
}
?>
You're soooooo close. Just use DateTime. It's perfect for this;
<?php
$today = new DateTime('2013-02-11');
$start_date = new DateTime('2013-02-11');
$end_date = new DateTime('2013-02-12');
$on_promo = (($start_date <= $today) && ($end_date >= $today));
if ($on_promo)
{
echo 'ON promo';
}
else
{
echo 'OFF promo';
}
?>