如何在PHP中检查字符串的日期格式?

11

我想要检查字符串是否符合这种时间格式:

Y-m-d H:i:s

如果不是那么就执行一些代码,例如:

if here will be condition do { this }
else do { this }

如何在PHP中实现这个条件语句?


这也是输入吗?这会被所有人使用吗?我问这个问题是因为为什么不直接创建日期呢?然后可以是任何格式。否则,正则表达式仍然是最好的方法,尽管它可能是无效的。闰年等等。 - Matt
在这种情况下,我要重复一句著名的话:有些人遇到问题时会想:“我知道,我会使用正则表达式。”现在他们有了两个问题。- Jamie Zawinski,我感觉这是其中之一。 - Matt
@Matt:正则表达式标签是我添加的,而不是kaspernov。 - Mchl
7个回答

21

preg_match正是你要找的,具体而言:

if(preg_match('/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/',$date)){
   //dothis
}else{
   //dothat
}

如果您真的只想要格式正确的日期,则

/\d{4}-[01]\d-[0-3]\d [0-2]\d:[0-5]\d:[0-5]\d/

21

如何在PHP中检查字符串的日期格式?

 if (DateTime::createFromFormat('Y-m-d G:i:s', $myString) !== FALSE) {
 echo 'true';
}                                                               

3
这个为什么不排在名单前面? - Captain Hypertext
未通过以下测试案例:$myString = '19-12-09 12:31:30'; if (DateTime::createFromFormat('Y-m-d G:i:s', $myString) !== FALSE) { echo 'true'; } - Siddhartha esunuri

18

你无法确定日期格式是 Y-m-d 还是 Y-d-m,甚至可能是 Y-d-dY-m-m。那么 2012-05-12 是什么意思?是5月12号还是12月5号?

不过,如果你可以接受这种不确定性,你可以这样做:

// convert it through strtotime to get the date and back.
if( $dt == date('Y-m-d H:i:s',strtotime($dt)) )
{
    // date is in fact in one of the above formats
}
else
{
    // date is something else.
}

尽管你可能希望查看是否 preg_match('/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/',$date) 在这种情况下更快。 我没有测试过。


7
抱歉,您的翻译请求有点不太正确。Y-m-d 是日期的标准格式,表示年-月-日。而将其翻译为“May the Decemberth of 2012”既不符合汉语表达习惯,也没有意义。如果您可以提供更清晰、更具体的翻译要求,我将很乐意为您服务。 - cwallenpoole
1
在我看来,比起正则表达式,这种方法更加优雅。 - Captain Hypertext

3
if (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $yourdate)) {
   // it's in the right format ...
} else {
  // not the right format ...
}

请注意,这仅检查日期字符串是否像一堆由冒号和破折号分隔的数字。它不会检查像“2011-02-31”(2月31日)或时间为“99:99:99”(99点?)等奇怪的情况。

谢谢,这解决了我的问题,而不必再提一个问题。 - Allerion

1

来自php.net

这里有一个很酷的函数可以验证mysql日期时间:

<?php
function isValidDateTime($dateTime)
{
    if (preg_match("/^(\d{4})-(\d{2})-(\d{2}) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/", $dateTime, $matches)) {
        if (checkdate($matches[2], $matches[3], $matches[1])) {
            return true;
        }
    }

    return false;
}
?>

0

你总是可以强制它的:

date('Y-m-d H:i:s',strtotime($str));

-1

答案可能涉及正则表达式。我建议先阅读这份文档,如果你仍然有困难,请回到这里。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接