php 检查字符串是否为日期的函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11029769/
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
Function to check if a string is a date
提问by Justin
I am trying to write a function to determine if a string is a date/time using PHP. Basically a valid date/time would look like:
我正在尝试编写一个函数来确定字符串是否是使用 PHP 的日期/时间。基本上有效的日期/时间如下所示:
2012-06-14 01:46:28
Obviously though its completely dynamic any of the values can change, but it should always be in form of XXXX-XX-XX XX:XX:XX, how can I write a regular expression to check for this pattern and return true if matched.
显然,尽管它是完全动态的,但任何值都可以更改,但它应该始终采用 的形式XXXX-XX-XX XX:XX:XX,我该如何编写正则表达式来检查此模式并在匹配时返回 true。
回答by Joey
If that's your whole string, then just try parsing it:
如果那是你的整个字符串,那么只需尝试解析它:
if (DateTime::createFromFormat('Y-m-d H:i:s', $myString) !== FALSE) {
// it's a date
}
回答by Bjoern
Here's a different approach without using a regex:
这是一种不使用正则表达式的不同方法:
function check_your_datetime($x) {
return (date('Y-m-d H:i:s', strtotime($x)) == $x);
}
回答by John Linhart
In case you don't know the date format:
如果您不知道日期格式:
/**
* Check if the value is a valid date
*
* @param mixed $value
*
* @return boolean
*/
function isDate($value)
{
if (!$value) {
return false;
}
try {
new \DateTime($value);
return true;
} catch (\Exception $e) {
return false;
}
}
var_dump(isDate('2017-01-06')); // true
var_dump(isDate('2017-13-06')); // false
var_dump(isDate('2017-02-06T04:20:33')); // true
var_dump(isDate('2017/02/06')); // true
var_dump(isDate('3.6. 2017')); // true
var_dump(isDate(null)); // false
var_dump(isDate(true)); // false
var_dump(isDate(false)); // false
var_dump(isDate('')); // false
var_dump(isDate(45)); // false
回答by Yogesh Mistry
Easiest way to check if a string is a date:
检查字符串是否为日期的最简单方法:
if(strtotime($date_string)){
// it's in date format
}
回答by Salman A
I use this function as a parameter to the PHP filter_varfunction.
我使用这个函数作为 PHPfilter_var函数的参数。
- It checks for dates in
yyyy-mm-dd hh:mm:ssformat - It rejects dates that match the pattern but still invalid (e.g. Apr 31)
- 它以
yyyy-mm-dd hh:mm:ss格式检查日期 - 它拒绝与模式匹配但仍然无效的日期(例如 4 月 31 日)
function filter_mydate($s) {
if (preg_match('@^(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)$@', $s, $m) == false) {
return false;
}
if (checkdate($m[2], $m[3], $m[1]) == false || $m[4] >= 24 || $m[5] >= 60 || $m[6] >= 60) {
return false;
}
return $s;
}
回答by cj5
Although this has an accepted answer, it is not going to effectively work in all cases. For example, I test date validation on a form field I have using the date "10/38/2013", and I got a valid DateObject returned, but the date was what PHP call "overflowed", so that "10/38/2013" becomes "11/07/2013". Makes sense, but should we just accept the reformed date, or force users to input the correct date? For those of us who are form validation nazis, We can use this dirty fix: https://stackoverflow.com/a/10120725/486863and just return false when the object throws this warning.
尽管这是一个公认的答案,但它不会在所有情况下都有效。例如,我在使用日期“10/38/2013”的表单字段上测试日期验证,并且返回了一个有效的 DateObject,但该日期是 PHP 所谓的“溢出”,因此“10/38/ 2013”变为“11/07/2013”。有道理,但我们应该只接受修改后的日期,还是强制用户输入正确的日期?对于我们这些表单验证纳粹分子,我们可以使用这个肮脏的修复:https: //stackoverflow.com/a/10120725/486863并且在对象抛出此警告时返回 false。
The other workaround would be to match the string date to the formatted one, and compare the two for equal value. This seems just as messy. Oh well. Such is the nature of PHP dev.
另一种解决方法是将字符串日期与格式化的日期匹配,并将两者进行比较以获得相等的值。这看起来同样混乱。那好吧。这就是 PHP 开发的本质。
回答by Gabor
In my project this seems to work:
在我的项目中,这似乎有效:
function isDate($value) {
if (!$value) {
return false;
} else {
$date = date_parse($value);
if($date['error_count'] == 0 && $date['warning_count'] == 0){
return checkdate($date['month'], $date['day'], $date['year']);
} else {
return false;
}
}
}
回答by emmanuel
if (strtotime($date)>strtotime(0)) { echo 'it is a date' }
if (strtotime($date)>strtotime(0)) { echo '这是一个日期' }
回答by José Rodrigues
回答by MERT DO?AN
If you have PHP 5.2 Joey's answer won't work. You need to extend PHP's DateTime class:
如果您有 PHP 5.2 Joey 的答案将不起作用。您需要扩展 PHP 的 DateTime 类:
class ExDateTime extends DateTime{
public static function createFromFormat($frmt,$time,$timezone=null){
$v = explode('.', phpversion());
if(!$timezone) $timezone = new DateTimeZone(date_default_timezone_get());
if(((int)$v[0]>=5&&(int)$v[1]>=2&&(int)$v[2]>17)){
return parent::createFromFormat($frmt,$time,$timezone);
}
return new DateTime(date($frmt, strtotime($time)), $timezone);
}
}
and than you can use this class without problems:
并且您可以毫无问题地使用此类:
ExDateTime::createFromFormat('d.m.Y G:i',$timevar);

