检查变量是否是 PHP 的有效日期

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

Check if variable is a valid date with PHP

phpdatestrtotime

提问by Alex

I am working on a script that will import some data from a CSV file. As I am doing this I want to be able to check a variable to see if it is a valid date string.

我正在编写一个脚本,该脚本将从 CSV 文件中导入一些数据。当我这样做时,我希望能够检查一个变量,看看它是否是一个有效的日期字符串。

I have seen several ways to check if a sting is a date, but most of them require you to now the format. I will not know the format that the date will in.

我已经看到了几种检查刺痛是否是日期的方法,但大多数方法都要求您现在使用格式。我不知道日期的格式。

right now I am using strtotime(), but this fails to easily

现在我正在使用 strtotime(),但这很容易失败

$field ="May";
if(strtotime($field)){
    echo "This is a date";
}

In this case, "May" was the persons first name, and not a date at all.

在这种情况下,“May”是人名,根本不是日期。

Can any one recommend more reliable function?

任何人都可以推荐更可靠的功能吗?

Edit based on questions from some of you.

根据你们中的一些人的问题进行编辑。

For a variable to pass as a "date" in my case, it would need to be specific to a day/month/year, so just "May" would be to vague to count.

在我的情况下,对于作为“日期”传递的变量,它需要特定于日/月/年,因此仅“五月”就显得含糊不清。

Based on that and Pauls good point below we can also test to see if the string contains a number, such as

基于这一点和保罗在下面的好点,我们还可以测试字符串是否包含数字,例如

$field ="May";
if(strtotime($field) && 1 === preg_match('~[0-9]~', $field)){
    echo "This is a date";
}else{
    echo "Nope not a date";
}

This seems to cover my immediate needs, but can any one spot any issues or suggest improvements?

这似乎满足了我的直接需求,但有人能发现任何问题或提出改进建议吗?

回答by saluce

Use date_parseand check the values of the returned array

使用date_parse并检查返回数组的值

$date = date_parse("May")

// ["year"] == FALSE
// ["month"] == 5
// ["day"] == FALSE

You can also pass those into checkdate.

您也可以将它们传递给checkdate

$date = date_parse($someString);
if ($date["error_count"] == 0 && checkdate($date["month"], $date["day"], $date["year"]))
    echo "Valid date";
else
    echo "Invalid date";

回答by Boris Guéry

I don't think there is a all-in-one answer to this problem. You may have different strategy depending on your use case.

我认为这个问题没有万能的答案。根据您的用例,您可能有不同的策略。

Your strtotime()is a perfect solution, but as you say, you may end up with false positive. Why? Because maymay be a word or a name. However, what is the result of strtotime('May')?

strtotime()是一个完美的解决方案,但正如您所说,您最终可能会出现误报。为什么?因为可能是一个词或一个名字。然而,结果是strtotime('May')什么呢?

echo date(DateTime::ISO8601, strtotime('May'));
2012-05-21T00:00:00+0200

So giving only the month will return a date of the current year and the current day starting at midnight with the given month. A possible solution would be to check if your string has the current day and/or the current year included, this way, you may check against to make sure your date is a fully qualified date and valid.

因此,仅给出月份将返回当前年份的日期和当前日期,该日期从给定月份的午夜开始。一个可能的解决方案是检查您的字符串是否包含当前日期和/或当前年份,这样,您可以检查以确保您的日期是完全合格的日期并且有效。

echo date(DateTime::ISO8601, strtotime('May Day')); // (strtotime() returns false)
1970-01-01T01:00:00+0100

echo date(DateTime::ISO8601, strtotime('May 21'));
2012-05-21T00:00:00+0200

A simple strpos()or even a regex should do the trick.

一个简单的strpos()甚至是正则表达式应该可以解决问题。

Howeverit is a bit odd and should be used only if you have no other way to do.

但是,它有点奇怪,只有在您没有其他方法时才应使用。

I believe that a better solution would be to define a set of valid format and interpolate the result to make sure that the date is valid.

我相信更好的解决方案是定义一组有效格式并插入结果以确保日期有效。

$validDateFormatPatterns = array(
 '[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}', // 21-05-2012, obviously this pattern is simple and would accept 05-21-2012,
 'the [0-9]{1,2}(th|st|nd|rd) (January|February|...|May|...|December) [0,9]{4}', // The 21st May 2012
);

You should try to cover most of the case and I'm sure you will be able to find regex that checks for most current date format.

您应该尝试涵盖大部分情况,我相信您将能够找到检查当前日期格式的正则表达式。

In any case, you may need to adapt your function from time to time because there is no easy way to make it bulletproof.

无论如何,您可能需要不时调整您的功能,因为没有简单的方法可以使其防弹。

回答by Bryan

I know this was asked a long time ago, but looking around for this and trying to avoid regex, I came up with this:

我知道很久以前就有人问过这个问题,但是环顾四周并试图避免使用正则表达式,我想出了这个:

function checkInputIsDate($date) {
    return (bool)strpbrk($date,1234567890) && strtotime($date);
}

This works because it takes away the issues posted above where only a month is passed into strtotimeby making sure there are numbers in the string with strpbrkas well as verifying strtotimeoutputs a date.

这是有效的,因为它通过strtotime确保字符串中有数字strpbrk以及验证strtotime输出日期来消除上面发布的仅传递一个月的问题。

And learned about a function I didn't know existed.

并了解了一个我不知道存在的功能。

Hope this helps someone.

希望这可以帮助某人。