检查有效日期类型


Check Valid date type

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

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

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

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

从$a开始,我可以使用爆炸函数得到23,11,但"六月"怎么样?使用上面的函数,'June'不是数字

为什么不让strtotime()进行验证?

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

否则,您必须重新构建strtotime()的功能才能进行验证——对我来说,这听起来像是一次徒劳的(也是一次巨大的)练习

作为接受相对日期(如"昨天"、"下个月的最后一天"甚至"-1年")的strtotime的替代方案,我建议使用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