Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php compare YYYY-mm-dd strings in php

Tags:

date

php

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';
}
?>
like image 383
Chris Muench Avatar asked Jul 18 '26 14:07

Chris Muench


1 Answers

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

See it in action

like image 81
John Conde Avatar answered Jul 20 '26 19:07

John Conde



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!