可能是这个问题已被问过,我已经搜索但仍然对我的问题没有信心..
我的问题是从字符串
检查有效日期$a='23-June-11'; //valid
$b='Normal String';//invalid
我想使用strtotime()转换$ a和$ b 在我这样做之前,当然我想验证$ a或$ b是否是有效的日期格式
从$ a我可以得到23,11使用爆炸功能,但是'六月'怎么样? 使用上面的函数,'June'不是数字
答案 0 :(得分:7)
为什么不让strtotime()
进行验证?
如果它是无效日期,它将返回false
。
否则,你必须重建strtotime()
的功能才能进行验证 - 对我来说听起来像是徒劳(和大)的练习。
答案 1 :(得分:1)
作为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