【问题标题】:Check Valid date type检查有效日期类型
【发布时间】:2011-06-24 15:02:37
【问题描述】:

可能是有人问过这个问题,我已经搜索过但对我的问题仍然没有信心..

我的问题是检查字符串中的有效日期

$a='23-June-11'; //valid
$b='Normal String';//invalid

我想使用 strtotime() 转换 $a 和 $b 在我这样做之前,我当然想验证 $a 或 $b 是否是有效的日期格式

从$a 我可以使用explode 函数得到23、11,但是'June' 呢? 使用上面的函数,'June' 不是数字

【问题讨论】:

    标签: php date validation


    【解决方案1】:

    为什么不让strtotime() 做验证呢?

    如果日期无效,它将返回 false

    否则,您必须重建 strtotime() 的功能才能进行验证 - 对我来说这听起来像是徒劳的(而且很大的)练习。

    【讨论】:

    • hmmm..你的意思是这样的验证吗? if(strtotime('somestring')){ //will return false
    • strtotime 有一个小问题。它将验证“+1 小时”和“本月的最后一天”等日期。
    • strtotime 不能用于验证日期。它如何在 2012 年 12 月 12 日这样的情况下工作。也不能用 strtotime 指定格式。
    • @Silver 很好,它满足了 OP 的要求……如果您有更好、更普遍的建议,请随时发布。如果它好,你会得到我的支持
    【解决方案2】:

    作为strtotime 的替代方案,它将接受诸如“昨天”、“下个月的最后一个日期”甚至“-1 年”等相对日期,我建议使用strptime。它用于根据您指定的格式解析日期字符串。

    在您的情况下,您需要strptime($date, '%d-%B-%y')

    例子:

    <?php
    
    // Set the locale as en_US to make sure that strptime uses English month names.
    setlocale(LC_TIME, 'en_US');
    
    $dates = array(
      '23-June-11',
      'Normal String'
    );
    
    foreach ( $dates as $date )
    {
      if ( strptime($date, '%d-%B-%y') )
      {
        echo $date . ' is a valid date' . PHP_EOL;
      }
      else
      {
        echo $date . ' is an invalid date' . PHP_EOL;
      }
    }
    

    输出:

    23-June-11 is a valid date
    Normal String is an invalid date
    

    【讨论】:

    • 非常好的简单解决方案
    • 根据stackoverflow.com/questions/254244/php-strptime-format-bug的说法,这个功能并不完善,我也不能用.. 注意:这个功能在Windows平台上没有实现。 (来自 php.net)我使用 windows paltform
    • @yukou - 这是因为正如strptime 文档所说,它取决于语言环境。如果您在顶部添加setlocale(LC_TIME, 'en_US');,它将强制该函数使用英文月份名称,否则,它将使用系统默认值,可能是另一种语言。
    • strptime 将报告正确的日期,如 30-02-2012。它也有其他限制。因此,它不是验证日期的完整证明方法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-28
    • 1970-01-01
    • 2012-03-15
    • 2013-01-20
    • 1970-01-01
    相关资源
    最近更新 更多