douxi4114 2013-02-11 22:09 采纳率: 100%
浏览 47
已采纳

php比较PHP中的YYYY-mm-dd字符串

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';
}
?>
  • 写回答

3条回答 默认 最新

  • duanan6043 2013-02-11 22:23
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?