使用 PHP 的 DateTime 类验证有效日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14504913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:24:57  来源:igfitidea点击:

Verify valid date using PHP's DateTime class

phpdatetime

提问by user1032531

Below is how I previously verified dates. I also had my own functions to convert date formats, however, now am using PHP's DateTime class so no longer need them. How should I best verify a valid date using DataTime? Please also let me know whether you think I should be using DataTime in the first place. Thanks

以下是我之前验证日期的方式。我也有自己的函数来转换日期格式,但是,现在我使用 PHP 的 DateTime 类,所以不再需要它们。我应该如何最好地使用 DataTime 验证有效日期?还请让我知道您是否认为我应该首先使用 DataTime。谢谢

PS. I am using Object oriented style, and not Procedural style.

附注。我使用的是面向对象的风格,而不是程序风格。

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);
}

回答by bitWorking

You can try this one:

你可以试试这个:

static public function verifyDate($date)
{
    return (DateTime::createFromFormat('m/d/Y', $date) !== false);
}

This outputs true/false. You could return DateTimeobject directly:

这输出真/假。您可以DateTime直接返回对象:

static public function verifyDate($date)
{
    return DateTime::createFromFormat('m/d/Y', $date);
}

Then you get back a DateTimeobject or false on failure.

然后你会DateTime在失败时返回一个对象或错误。

UPDATE:

更新:

Thanks to Elvis Ciotti who showed that createFromFormat accepts invalid dates like 45/45/2014. More information on that: https://stackoverflow.com/a/10120725/1948627

感谢 Elvis Ciotti,他表明 createFromFormat 接受无效日期,例如 45/45/2014。更多信息:https: //stackoverflow.com/a/10120725/1948627

I've extended the method with a strict check option:

我使用严格的检查选项扩展了该方法:

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;
}

回答by Faiyaz Alam

With DateTime you can make the shortest date&time validator for all formats.

使用 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

function was copied from this answeror php.net

函数是从此答案php.net复制的

回答by shadyyx

You could check this resource: http://php.net/manual/en/datetime.getlasterrors.php

你可以检查这个资源:http: //php.net/manual/en/datetime.getlasterrors.php

The PHP codes states:

PHP 代码指出:

try {
    $date = new DateTime('asdfasdf');
} catch (Exception $e) {
    print_r(DateTime::getLastErrors());
    // or
    echo $e->getMessage();
}

回答by boctulus

Try this:

尝试这个:

  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);
  }

回答by bluepinto

$date[] = '20/11/2569';     
$date[] = 'lksdjflskdj'; 
$date[] = '11/21/1973 10:20:30';
$date[] = '21/11/1973 10:20:30';
$date[] = " ' or uid like '%admin%"; 
foreach($date as $dt)echo date('Y-m-d H:i:s', strtotime($dt))."\n";

Output

输出

1970-01-01 05:30:00
1970-01-01 05:30:00
1970-01-01 05:30:00
1973-11-21 10:20:30
1970-01-01 05:30:00
1970-01-01 05:30:00

回答by julius patta

I needed to allow user input in (n) different, known, formats...including microtime. Here is an example with 3.

我需要允许用户以 (n) 种不同的、已知的格式输入......包括微时间。这是一个例子,3。

function validateDate($date)
{
    $formats = ['Y-m-d','Y-m-d H:i:s','Y-m-d H:i:s.u'];
    foreach($formats as $format) {
        $d = DateTime::createFromFormat($format, $date);
        if ($d && $d->format($format) == $date) return true;
    }
    return false;
}