检查变量是否是PHP的有效日期 [英] Check if variable is a valid date with PHP
问题描述
我正在处理一个脚本,它会从CSV文件导入一些数据。当我这样做,我想能够检查一个变量,看看它是否是一个有效的日期字符串。
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.
我已经看到几种方法来检查刺痛是否是一个日期,但是大部分都需要你现在的格式。我不会知道日期的格式。
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.
现在我正在使用strtotime(),但这不能轻松地
right now I am using strtotime(), but this fails to easily
$field ="May";
if(strtotime($field)){
echo "This is a date";
}
在这种情况下,May是人名,而不是日期。
In this case, "May" was the persons first name, and not a date at all.
任何人都可以推荐更可靠的功能?
Can any one recommend more reliable function?
根据您的一些人的问题编辑
在我的情况下作为日期通过,它将需要具体到一个/每月/年,所以只是五月将是模糊的。
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.
根据以下的Pauls好点,我们还可以测试字符串是否包含一个数字,例如
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?
推荐答案
使用 date_parse 并检查返回的数组的值
Use date_parse and check the values of the returned array
$date = date_parse("May")
// ["year"] == FALSE
// ["month"] == 5
// ["day"] == FALSE
你也可以将它们传递到 checkdate 。
You can also pass those into checkdate.
$date = date_parse($someString);
if ($date["error_count"] == 0 && checkdate($date["month"], $date["day"], $date["year"]))
echo "Valid date";
else
echo "Invalid date";
这篇关于检查变量是否是PHP的有效日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!