Php compare YYYY-mm-dd strings in php

I came across php code comparing dates in YYYY-mm-dd format as strings. It works? This seems to work in simple cases, but I'm not sure if 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';
}
?>

      

+3


source to share


3 answers


When comparing strings in PHP using a value greater or less, it compares them alphabetically.

Alphabetically 2013-02-10

preceded by2013-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

      



Note, however, that if the strings are numeric they will cast them as integers

var_dump('11' > '101'); // produces false
var_dump('a11' > 'a101'); // produces true
var_dump('11a' > '101a'); // produces true

      

So if you are using the format YYYY-MM-DD

you can compare the two dates perfectly, but I really don't recommend relying on that. Someone could provide a date, for example 2013-2-11

(note that the month has no leading 0

) and it will drop the logic entirely. It is much better to accept John Conde's offer and useDateTime

+2


source


You are so close. Just use DateTime . This is 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';
}
?>

      



Look at the action

+4


source


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';
}
?>

      

+1


source







All Articles