php php日期验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12030810/
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
php date validation
提问by Pablo Lopez
Im trying to to set up a php date validation (MM/DD/YYYY) but I'm having issues. Here is a sample of what I got:
我正在尝试设置 php 日期验证 (MM/DD/YYYY),但我遇到了问题。这是我得到的样本:
$date_regex = '%\A(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d\z%';
$test_date = '03/22/2010';
if (preg_match($date_regex, $test_date,$_POST['birthday']) ==true) {
$errors[] = 'user name most have no spaces';`
回答by Nicolás Ozimica
You could use checkdate. For example, something like this:
您可以使用checkdate。例如,这样的事情:
$test_date = '03/22/2010';
$test_arr = explode('/', $test_date);
if (checkdate($test_arr[0], $test_arr[1], $test_arr[2])) {
// valid date ...
}
A more paranoid approach, that doesn't blindly believe the input:
一种更偏执的方法,即不盲目相信输入:
$test_date = '03/22/2010';
$test_arr = explode('/', $test_date);
if (count($test_arr) == 3) {
if (checkdate($test_arr[0], $test_arr[1], $test_arr[2])) {
// valid date ...
} else {
// problem with dates ...
}
} else {
// problem with input ...
}
回答by salathe
You can use some methods of the DateTimeclass, which might be handy; namely, DateTime::createFromFormat()in conjunction with DateTime::getLastErrors().
您可以使用DateTime类的一些方法,这可能很方便;即,DateTime::createFromFormat()结合DateTime::getLastErrors()。
$test_date = '03/22/2010';
$date = DateTime::createFromFormat('m/d/Y', $test_date);
$date_errors = DateTime::getLastErrors();
if ($date_errors['warning_count'] + $date_errors['error_count'] > 0) {
$errors[] = 'Some useful error message goes here.';
}
This even allows us to see what actually caused the date parsing warnings/errors (look at the warningsand errorsarrays in $date_errors).
这甚至允许我们查看实际导致日期解析警告/错误的原因(查看 中的warnings和errors数组$date_errors)。
回答by Joel
Though checkdateis good, this seems much concise function to validate and also you can give formats. [Source]
虽然checkdate很好,但这似乎是一个非常简洁的验证功能,您还可以提供格式。[来源]
function validateDate($date, $format = 'Y-m-d H:i:s') {
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
function was copied from this answeror php.net
The extra ->format()is needed for cases where the date is invalid but createFromFormatstill manages to create a DateTime object. For example:
->format()对于日期无效但createFromFormat仍设法创建 DateTime 对象的情况,需要
额外的内容。例如:
// Gives "2016-11-10 ..." because Thursday falls on Nov 10
DateTime::createFromFormat('D M j Y', 'Thu Nov 9 2016');
// false, Nov 9 is a Wednesday
validateDate('Thu Nov 9 2016', 'D M j Y');
回答by d.raev
回答by user2028418
Use it:
用它:
function validate_Date($mydate,$format = 'DD-MM-YYYY') {
if ($format == 'YYYY-MM-DD') list($year, $month, $day) = explode('-', $mydate);
if ($format == 'YYYY/MM/DD') list($year, $month, $day) = explode('/', $mydate);
if ($format == 'YYYY.MM.DD') list($year, $month, $day) = explode('.', $mydate);
if ($format == 'DD-MM-YYYY') list($day, $month, $year) = explode('-', $mydate);
if ($format == 'DD/MM/YYYY') list($day, $month, $year) = explode('/', $mydate);
if ($format == 'DD.MM.YYYY') list($day, $month, $year) = explode('.', $mydate);
if ($format == 'MM-DD-YYYY') list($month, $day, $year) = explode('-', $mydate);
if ($format == 'MM/DD/YYYY') list($month, $day, $year) = explode('/', $mydate);
if ($format == 'MM.DD.YYYY') list($month, $day, $year) = explode('.', $mydate);
if (is_numeric($year) && is_numeric($month) && is_numeric($day))
return checkdate($month,$day,$year);
return false;
}
回答by FirmView
Nicolas solution is best. If you want in regex,
尼古拉斯解决方案是最好的。如果你想在正则表达式中,
try this,
尝试这个,
this will validate for, 01/01/1900 through 12/31/2099 Matches invalid dates such as February 31st Accepts dashes, spaces, forward slashes and dots as date separators
这将验证 01/01/1900 到 12/31/2099 匹配无效日期,例如 2 月 31 日接受破折号、空格、正斜杠和点作为日期分隔符
(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)[0-9]{2}
回答by Jared Drake
REGEX should be a last resort. PHP has a few functions that will validate for you. In your case, checkdate is the best option. http://php.net/manual/en/function.checkdate.php
REGEX 应该是最后的手段。PHP 有一些函数可以为您验证。在您的情况下, checkdate 是最好的选择。http://php.net/manual/en/function.checkdate.php
回答by Rich R
I know this is an older post, but I've developed the following function for validating a date:
我知道这是一篇较旧的帖子,但我开发了以下用于验证日期的函数:
function IsDateTime($aDateTime) {
try {
$fTime = new DateTime($aDateTime);
$fTime->format('m/d/Y H:i:s');
return true;
}
catch (Exception $e) {
return false;
}
}
回答by Dennis
Not sure if this answer the question or going to help....
不确定这是否回答了问题或是否会有所帮助....
$dt = '6/26/1970' ; // or // '6.26.1970' ;
$dt = preg_replace("([.]+)", "/", $dt);
$test_arr = explode('/', $dt);
if (checkdate($test_arr[0], $test_arr[1], $test_arr[2]) && preg_match("/[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}/", $dt))
{ echo(date('Y-m-d', strtotime("$dt")) . "<br>"); }
else
{ echo "no good...format must be in mm/dd/yyyy"; }
回答by Plusce
We can use simple "date" input type, like below:
我们可以使用简单的“日期”输入类型,如下所示:
Birth date: <input type="date" name="userBirthDate" /><br />
Then we can link DateTime interface with built-in function 'explode':
然后我们可以将 DateTime 接口与内置函数 'explode' 链接:
public function validateDate()
{
$validateFlag = true;
$convertBirthDate = DateTime::createFromFormat('Y-m-d', $this->birthDate);
$birthDateErrors = DateTime::getLastErrors();
if ($birthDateErrors['warning_count'] + $birthDateErrors['error_count'] > 0)
{
$_SESSION['wrongDateFormat'] = "The date format is wrong.";
}
else
{
$testBirthDate = explode('-', $this->birthDate);
if ($testBirthDate[0] < 1900)
{
$validateFlag = false;
$_SESSION['wrongDateYear'] = "We suspect that you did not born before XX century.";
}
}
return $validateFlag;
}
I tested it on Google Chrome and IE, everything works correctly. Furthemore, Chrome display simple additional interface. If you don't write anything in input or write it in bad format (correctly is following: '1919-12-23'), you will get the first statement. If you write everything in good format, but you type wrong date (I assumed that nobody could born before XX century), your controller will send the second statement.
我在谷歌浏览器和 IE 上测试过,一切正常。此外,Chrome 显示简单的附加界面。如果您没有在输入中写入任何内容或以错误的格式写入(正确如下:'1919-12-23'),您将获得第一条语句。如果您以良好的格式编写所有内容,但是您输入了错误的日期(我认为没有人可以在 XX 世纪之前出生),您的控制器将发送第二条语句。

