php 正确确定日期字符串是否为该格式的有效日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19271381/
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 19:09:44  来源:igfitidea点击:

Correctly determine if date string is a valid date in that format

phpdatedatetime

提问by Marty Wallace

I'm receiving a date string from an API, and it is formatted as yyyy-mm-dd.

我从 API 接收日期字符串,它的格式为yyyy-mm-dd.

I am currently using a regex to validate the string format, which works ok, but I can see some cases where it could be a correct format according to the string but actually an invalid date. i.e. 2013-13-01, for example.

我目前正在使用正则表达式来验证字符串格式,它可以正常工作,但我可以看到一些情况,根据字符串它可能是正确的格式,但实际上是无效的日期。即2013-13-01,例如。

Is there a better way in PHP to take a string such as 2013-13-01and tell if it is a valid date or not for the format yyyy-mm-dd?

PHP 中是否有更好的方法来获取字符串2013-13-01并判断它是否是格式的有效日期yyyy-mm-dd

回答by Amal Murali

You can use DateTimeclass for this purpose:

您可以DateTime为此目的使用类:

function validateDate($date, $format = 'Y-m-d')
{
    $d = DateTime::createFromFormat($format, $date);
    // The Y ( 4 digits year ) returns TRUE for any integer with any number of digits so changing the comparison from == to === fixes the issue.
    return $d && $d->format($format) === $date;
}

[Function taken from this answer. Also on php.net. Originally written by Glavi?.]

[这个答案中获取的功能。也在php.net 上。最初由Glavi编写. ]



Test cases:

测试用例:

var_dump(validateDate('2013-13-01'));  // false
var_dump(validateDate('20132-13-01')); // false
var_dump(validateDate('2013-11-32'));  // false
var_dump(validateDate('2012-2-25'));   // false
var_dump(validateDate('2013-12-01'));  // true
var_dump(validateDate('1970-12-01'));  // true
var_dump(validateDate('2012-02-29'));  // true
var_dump(validateDate('2012', 'Y'));   // true
var_dump(validateDate('12012', 'Y'));  // false

Demo!

演示!

回答by arsh

Determine if any string is a date

确定任何字符串是否为日期

function checkIsAValidDate($myDateString){
    return (bool)strtotime($myDateString);
}

回答by vineet

Use in simple way with php prebuilt function:

以简单的方式使用 php 预建函数:

function checkmydate($date) {
  $tempDate = explode('-', $date);
  // checkdate(month, day, year)
  return checkdate($tempDate[1], $tempDate[2], $tempDate[0]);
}

Test

测试

   checkmydate('2015-12-01'); //true
   checkmydate('2015-14-04'); //false

回答by migli

Determine if string is a date, even if string is a non-standard format

确定字符串是否为日期,即使字符串是非标准格式

(strtotime doesn't accept any custom format)

(strtotime 不接受任何自定义格式)

<?php
function validateDateTime($dateStr, $format)
{
    date_default_timezone_set('UTC');
    $date = DateTime::createFromFormat($format, $dateStr);
    return $date && ($date->format($format) === $dateStr);
}

// These return true
validateDateTime('2001-03-10 17:16:18', 'Y-m-d H:i:s');
validateDateTime('2001-03-10', 'Y-m-d');
validateDateTime('2001', 'Y');
validateDateTime('Mon', 'D');
validateDateTime('March 10, 2001, 5:16 pm', 'F j, Y, g:i a');
validateDateTime('March 10, 2001, 5:16 pm', 'F j, Y, g:i a');
validateDateTime('03.10.01', 'm.d.y');
validateDateTime('10, 3, 2001', 'j, n, Y');
validateDateTime('20010310', 'Ymd');
validateDateTime('05-16-18, 10-03-01', 'h-i-s, j-m-y');
validateDateTime('Monday 8th of August 2005 03:12:46 PM', 'l jS \of F Y h:i:s A');
validateDateTime('Wed, 25 Sep 2013 15:28:57', 'D, d M Y H:i:s');
validateDateTime('17:03:18 is the time', 'H:m:s \i\s \t\h\e \t\i\m\e');
validateDateTime('17:16:18', 'H:i:s');

// These return false
validateDateTime('2001-03-10 17:16:18', 'Y-m-D H:i:s');
validateDateTime('2001', 'm');
validateDateTime('Mon', 'D-m-y');
validateDateTime('Mon', 'D-m-y');
validateDateTime('2001-13-04', 'Y-m-d');

回答by galki

This option is not only simple but also accepts almost any format, although with non-standard formats it can be buggy.

此选项不仅简单,而且几乎可以接受任何格式,尽管使用非标准格式可能会有问题。

$timestamp = strtotime($date);
return $timestamp ? $date : null;

回答by Suvash sarker

You can also Parse the date for month date and year and then you can use the PHP function checkdate()which you can read about here: http://php.net/manual/en/function.checkdate.php

您还可以解析月份日期和年份的日期,然后您可以使用checkdate()您可以在此处阅读的 PHP 函数:http: //php.net/manual/en/function.checkdate.php

You can also try this one:

你也可以试试这个:

$date="2013-13-01";

if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$date))
    {
        echo 'Date is valid';
    }else{
        echo 'Date is invalid';
    }

回答by Victor Schr?der

I have this thing that, even with PHP, I like to find functionalsolutions. So, for example, the answer given by @migli is really a good one, highly flexible and elegant.

我有一个东西,即使使用 PHP,我也喜欢找到函数式解决方案。因此,例如,@migli 给出的答案确实很好,高度灵活且优雅。

But it has a problem: what if you need to validate a lot of DateTime strings with the same format? You would have to repeat the format all over the place, what goes against the DRYprinciple. We could put the format in a constant, but still, we would have to pass the constant as an argument to every function call.

但它有一个问题:如果需要验证大量相同格式的 DateTime 字符串怎么办?你必须到处重复这种格式,这违背了DRY原则。我们可以将格式放在一个常量中,但仍然必须将常量作为参数传递给每个函数调用。

But fear no more! We can use curryingto our rescue! PHP doesn't make this task pleasant, but it's still possible to implement currying with PHP:

但是不要再害怕了!我们可以使用柯里化来拯救我们!PHP 并没有让这个任务变得愉快,但仍然可以用 PHP 实现柯里化:

<?php
function validateDateTime($format)
{
    return function($dateStr) use ($format) {
        $date = DateTime::createFromFormat($format, $dateStr);
        return $date && $date->format($format) === $dateStr;
    };
}

So, what we just did? Basically we wrapped the function body in an anonymous and returned such function instead. We can call the validation function like this:

那么,我们刚刚做了什么?基本上,我们将函数体包装在匿名中并返回这样的函数。我们可以这样调用验证函数:

validateDateTime('Y-m-d H:i:s')('2017-02-06 17:07:11'); // true

Yeah, not a big difference... but the real power comes from the partially applied function, made possible by currying:

是的,差别不大......但真正的力量来自部分应用函数,通过柯里化实现:

// Get a partially applied function
$validate = validateDateTime('Y-m-d H:i:s');

// Now you can use it everywhere, without repeating the format!
$validate('2017-02-06 17:09:31'); // true
$validate('1999-03-31 07:07:07'); // true
$validate('13-2-4 3:2:45'); // false

Functional programming FTW!

函数式编程 FTW!

回答by sdotbertoli

Accordling with cl-sah's answer, but this sound better, shorter...

与 cl-sah 的回答一致,但这听起来更好,更短......

function checkmydate($date) {
  $tempDate = explode('-', $date);
  return checkdate($tempDate[1], $tempDate[2], $tempDate[0]);
}

Test

测试

checkmydate('2015-12-01');//true
checkmydate('2015-14-04');//false

回答by sdotbertoli

The easiest way to check if given date is valid probably converting it to unixtime using strtotime, formatting it to the given date's format, then comparing it:

检查给定日期是否有效的最简单方法可能是使用 将其转换为 unixtime strtotime,将其格式化为给定日期的格式,然后进行比较:

function isValidDate($date) { return date('Y-m-d', strtotime($date)) === $date; }

function isValidDate($date) { return date('Y-m-d', strtotime($date)) === $date; }

Of course you can use regular expression to check for validness, but it will be limited to given format, every time you will have to edit it to satisfy another formats, and also it will be more than required. Built-in functions is the best way (in most cases) to achieve jobs.

当然您可以使用正则表达式来检查有效性,但它会仅限于给定的格式,每次您都必须对其进行编辑以满足其他格式,而且会超出要求。内置函数是(在大多数情况下)实现工作的最佳方式。

回答by Barvajz

I'm afraid that most voted solution (https://stackoverflow.com/a/19271434/3283279) is not working properly. The fourth test case (var_dump(validateDate('2012-2-25')); // false) is wrong. The date is correct, because it corresponds to the format - the mallows a month with or withoutleading zero (see: http://php.net/manual/en/datetime.createfromformat.php). Therefore a date 2012-2-25is in format Y-m-dand the test case must be true not false.

恐怕大多数投票的解决方案(https://stackoverflow.com/a/19271434/3283279)无法正常工作。第四个测试用例 (var_dump(validateDate('2012-2-25')); // false) 是错误的。日期是正确的,因为它对应于格式 - m允许带或不带前导零的月份(请参阅:http: //php.net/manual/en/datetime.createfromformat.php)。因此,日期2012-2-25的格式为Ymd,并且测试用例必须为真而非假。

I believe that better solution is to test possible error as follows:

我相信更好的解决方案是测试可能的错误如下:

function validateDate($date, $format = 'Y-m-d') {
    DateTime::createFromFormat($format, $date);
    $errors = DateTime::getLastErrors();

    return $errors['warning_count'] === 0 && $errors['error_count'] === 0;
}