以下是我之前验证日期的方式.我也有自己的函数来转换日期格式,但是,现在使用PHP的DateTime类,所以不再需要它们.我应该如何使用DataTime最好地验证有效日期?还请让我知道您是否认为我应该首先使用DataTime.谢谢
PS.我使用面向对象的风格,而不是程序风格.
static public function verifyDate($date)
{
//Given m/d/Y and returns date if valid, else NULL.
$d=explode('/',$date);
return ((isset($d[0])&&isset($d[1])&&isset($d[2]))?(checkdate($d[0],$d[1],$d[2])?$date:NULL):NULL);
}
Run Code Online (Sandbox Code Playgroud)
bit*_*ing 62
你可以尝试这个:
static public function verifyDate($date)
{
return (DateTime::createFromFormat('m/d/Y', $date) !== false);
}
Run Code Online (Sandbox Code Playgroud)
这输出真/假.你可以DateTime直接返回对象:
static public function verifyDate($date)
{
return DateTime::createFromFormat('m/d/Y', $date);
}
Run Code Online (Sandbox Code Playgroud)
然后你得到一个DateTime对象或失败时假.
更新:
感谢Elvis Ciotti,他表示createFromFormat接受像45/45/2014这样的无效日期.有关该问题的更多信息:https://stackoverflow.com/a/10120725/1948627
我已经使用严格的检查选项扩展了该方法:
static public function verifyDate($date, $strict = true)
{
$dateTime = DateTime::createFromFormat('m/d/Y', $date);
if ($strict) {
$errors = DateTime::getLastErrors();
if (!empty($errors['warning_count'])) {
return false;
}
}
return $dateTime !== false;
}
Run Code Online (Sandbox Code Playgroud)
sha*_*yyx 10
您可以查看此资源:http://php.net/manual/en/datetime.getlasterrors.php
PHP代码说明:
try {
$date = new DateTime('asdfasdf');
} catch (Exception $e) {
print_r(DateTime::getLastErrors());
// or
echo $e->getMessage();
}
Run Code Online (Sandbox Code Playgroud)
Fai*_*lam 10
使用DateTime,您可以为所有格式制作最短的日期和时间验证器.
function validateDate($date, $format = 'Y-m-d H:i:s')
{
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
var_dump(validateDate('2012-02-28 12:12:12')); # true
var_dump(validateDate('2012-02-30 12:12:12')); # false
Run Code Online (Sandbox Code Playgroud)
试试这个:
function is_valid_date($date,$format='dmY')
{
$f = DateTime::createFromFormat($format, $date);
$valid = DateTime::getLastErrors();
return ($valid['warning_count']==0 and $valid['error_count']==0);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
47580 次 |
| 最近记录: |