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

问题描述 投票:0回答:8

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

Y-m-d H:i:s

如果没有,则执行一些代码,例如

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

如何在 PHP 中执行此条件?

php regex preg-match
8个回答
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';
}                                                               

18
投票

你不知道。无法分辨是

Y-m-d
还是
Y-d-m
,甚至是
Y-d-d
vs
Y-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)
在这方面是否更快。没测试过。


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 点钟?)之类的奇怪现象。


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));

0
投票

PHP 中唯一的事情是将其转换为日期时间,然后从日期时间返回字符串。例如

$datetime = \DateTimeImmutable::createFromFormat('Y-m-d G:i:s', $userDateTimeInput);

if ($datetime && $datetime->format('Y-m-d G:i:s') === $userDateTimeInput) {
  // $datetime is not false and we have a correct date in correct format
}

-1
投票

答案可能涉及到正则表达式。我建议您阅读本文档,如果仍有问题,请返回此处。

© www.soinside.com 2019 - 2024. All rights reserved.