MySQL:如何检查字符串是否为有效的DATE,TIME或DATETIME

时间:2010-04-22 11:10:21

标签: php mysql validation datetime

当我尝试将值放入无效的DATE字段时,MySQL似乎使用了0000-00-00。有没有办法在没有更新DATE字段的情况下“检查”?从例如PHP开始呢?

是的,有没有办法可以查询MySQL服务器并询问“嘿,这个日期,时间或日期对您有效吗?”

或者是否有更好的方法可以做到这一点?

13 个答案:

答案 0 :(得分:6)

您可以根据要使用的格式解析日期,然后调用checkdate来测试它是否是有效日期。请务必阅读http://php.net/manual/en/function.checkdate.php上的评论。

答案 1 :(得分:6)

我在我的应用程序中使用这种语法,它就像魅力一样!

SELECT DATE('2013-09-31') AS valid;

我的系统是带有PHP 5.5和MySQL 5.6.16的Win7x64

答案 2 :(得分:3)

您可以使用“常量”查询,而无需使用临时表和测试字段:

mysql> select day('2010-02-31 00:00:00');
+----------------------------+
| day('2010-02-31 00:00:00') |
+----------------------------+
|                       NULL | 
+----------------------------+

答案 3 :(得分:3)

由于问题陈述 MySQL ,这是一个 MySQL 解决方案:

由于需要考虑所有不同的可能日期格式,因此很难验证字段是否为日期。但如果您知道字段日期格式是以下之一:

'yyyy-mm-dd'
'yyyy-mm-dd hh:mm:ss'
'yyyy-mm-dd whatever'

此代码可以帮助您:

 SELECT count(*) FROM `table` 
 WHERE DATE(STR_TO_DATE(`column`, '%Y-%m-%d')) IS NOT NULL
 AND `column` NOT REGEXP '^[0-9\.]+$'

基本上:

  • 第一个条件告诉您是否是日期,但遗憾的是不排除数字(例如:DATE(STR_TO_DATE(**1**, '%Y-%m-%d')) = '2001-00-00'
  • 第二个确保排除数字,只留下符合上述格式的日期。

如果count(*)>0,则为日期,如果为0,则为其他日期。

注意 只要您事先知道它们遵循的格式(我知道情况并非总是如此但仍然有用),此方法适用于任何日期格式的字符串。只需替换查询

中的格式a priori即可

答案 4 :(得分:2)

如果为MySQL服务器选择不允许无效日期值的服务器模式,则包含这种格式错误的日期表示的查询将导致错误而不是(默默地)假设0002 见http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html

e.g。

$pdo = new PDO('mysql:host=localhost;dbname=test', 'localonly', 'localonly'); 
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

$pdo->exec('CREATE TEMPORARY TABLE foo (id int auto_increment, d datetime, primary key(id))');

$query = "INSERT INTO foo (d) VALUES ('2010-02-31 12:15:18')";
foreach( array('ALLOW_INVALID_DATES', 'STRICT_ALL_TABLES') as $mode ) {
  echo $mode, ": "; flush();
  $pdo->exec("SET SESSION sql_mode='$mode'");
  $pdo->exec($query);
  echo "Ok.\n";
}

打印

ALLOW_INVALID_DATES: Ok.
STRICT_ALL_TABLES: 
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '2010-02-31 12:15:18' for column 'd' at row 1' in [...]

答案 5 :(得分:1)

SELECT WEEK(col) IS NOT NULL AS valid;

或其中一个:

SELECT DAYNAME(col) IS NOT NULL AS valid;
SELECT TO_DAYS(col) IS NOT NULL AS valid;
SELECT TO_SECONDS(col) IS NOT NULL AS valid;
SELECT WEEKDAY(col) IS NOT NULL AS valid;
SELECT WEEKOFYEAR(col) IS NOT NULL AS valid;
SELECT YEARWEEK(col) IS NOT NULL AS valid;

答案 6 :(得分:1)

我这样做:

def method_a(self):
 x = X(self)

答案 7 :(得分:0)

在php中使用此功能来检查有效日期:

function valid_date($date) {
    return (preg_match("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date));
}

或者@VolkerK说如果在数据库中插入无效日期,它将被存储为0000-00-00,所以你也可以这样做:

SELECT * FROM table WHERE date_field > '0000-00-00'

答案 8 :(得分:0)

一个简单的PHP函数,它将验证“date”和“datetime”的MySQL数据类型 在随后的代码示例中(chk_MySQL_Datetime)。它通过使用createFromFormat()来验证 如果此日期/日期时间失败,则为日期/日期时间创建日期/日期时间 是无效的。如果创建了日期对象,则使用创建的格式化字符串 date_format()并与日期/时间进行比较。 如果字符串相等,则日期/日期时间有效。 如果不相等,则日期/日期时间无效。这种比较 是必要的,因为createFromFormat()将接受2009/02/29 09:85作为有效的日期时间 但MySQL不会。

以下代码包含一个示例/测试用例,显示针对MySQL数据库的使用和测试。 要使用该示例,您必须使用对数据库的调用替换$ database-> domysql_query()。 回声的输出包含在echo语句之后的注释中。

<?php
/**
 * Returns false if MySQL date or datetime value would be stored as
 * 0000-00-00  or 0000-00-00 00:00:00.
 * @param string $fmt - createFromFormat format of MySQL datetime value
 * to be tested. see http://www.php.net/manual/en/datetime.createfromformat.php
 * @param string $datetime MySQL datetime value
 * to be tested.
 * @return DateTime object formatted according to $fmt or FALSE if not
 * valid MySQL datetime value (would be inserted into the database
 * 0000-00-00 00:00:00);
 */
function chk_MySQL_Datetime($fmt, $datetime) {
    global $fmtdatetime;  // for example only
    $ckdate = DateTime::createFromFormat($fmt, $datetime);
    if ($ckdate !== FALSE) {
        $fmtdatetime = date_format($ckdate, $fmt);
        if ($fmtdatetime != $datetime) {
            $ckdate = FALSE;
        }
    }

    return $ckdate;
}
/*  Example/test of  chk_MySQL_Datetime */
/**
 * Creates table datetimetest if it doesn't exist
 * and insert a record in primary index of type datetime
 * then select record inserted and return result as a formated string.
 * @global type $database - addressibility to database functions
 * @global type $mysqlenum - MySql errornumber of last operation
 * @global type $fmtdatetime - $datetime formatted by date_format
 * @param type $datetime - datetime vale to be set
 * @return string of what was inserted
 */
function insert_in_table($datetime) {
    global $database, $mysqlenum, $fmtdatetime;
    $sql = "CREATE TABLE IF NOT EXISTS `datetimetest` (
  `MySQL_datetime` datetime NOT NULL COMMENT 'datetime created by MySQL',
  `in_datetime` varchar(90) NOT NULL COMMENT 'date time string',
  `fmtdatetime` varchar(90) NOT NULL COMMENT 'Output of createFromFormat',
  PRIMARY KEY (`MySQL_datetime`)
) ;";
    $result = $database->domysql_query($sql, $database->connection, true);

    $sql = "DELETE FROM `datetimetest`  WHERE MySQL_datetime='$datetime' OR `MySQL_datetime` = '0000-00-00 00:00:00'; ";
    $result = $database->domysql_query($sql, $database->connection, false);
    $sql = "INSERT INTO `datetimetest` (MySQL_datetime, in_datetime, fmtdatetime)
       VALUES ('$datetime', '$datetime', '$fmtdatetime')";
    $result = $database->domysql_query($sql, $database->connection, false);
    $sql = "SELECT * FROM `datetimetest`  WHERE MySQL_datetime='$datetime' OR `MySQL_datetime` = '0000-00-00 00:00:00'; ";
    $result = $database->domysql_query($sql, $database->connection, false);
    $contxa = mysql_fetch_assoc($result);

    $ret = " Inserted datetime = " . $contxa['in_datetime'] . "," .
            " MySQL stored " . $contxa['MySQL_datetime'] .
            ", fmtdatetime = " . $contxa['fmtdatetime'] . "<br>";
    return $ret;
}

        global $fmtdatetime;
        echo('<br>');
        $format = 'Y-m-d';
        $datetime = '2009-02-15'; // valid date
        $date = chk_MySQL_Datetime($format, $datetime);
        echo "Format: $format; datetime is " . ($date ? 'valid' : 'invalid' ) . " Expected $datetime is " . $fmtdatetime . "<br>";
 //echo output = Format: Y-m-d; datetime is valid Expected 2009-02-15 is 2009-02-15

        $result = insert_in_table($datetime);
        echo $result . "<br>";
 //echo output = Inserted datetime = 2009-02-15, MySQL stored 2009-02-15 00:00:00, fmtdatetime = 2009-02-15

        $datetime = '2009-02-29'; //invalid date
        $date = chk_MySQL_Datetime($format, $datetime);
        echo "Format: $format; datetime is " . ($date ? 'valid' : 'invalid' ) . " Expected $datetime is " . $fmtdatetime . "<br>";
 //echo output = Format: Y-m-d; datetime is invalid Expected 2009-02-29 is 2009-03-01

        $result = insert_in_table($datetime);
        echo $result . "<br>";
 //echo output =  Inserted datetime = 2009-02-29, MySQL stored 0000-00-00 00:00:00, fmtdatetime = 2009-03-01

        $format = 'Y-m-d H:i';
        $datetime = '2009-02-15 14:20';
        $date = chk_MySQL_Datetime($format, $datetime);
        echo "Format: $format; datetime is " . ($date ? 'valid' : 'invalid' ) . " Expected $datetime is " . $fmtdatetime . "<br>";
//echo output = Format: Y-m-d H:i; datetime is valid Expected 2009-02-15 14:20 is 2009-02-15 14:20

        $result = insert_in_table($datetime);
        echo $result . "<br>";
//echo output = Inserted datetime = 2009-02-15 14:20, MySQL stored 2009-02-15 14:20:00, fmtdatetime = 2009-02-15 14:20

        $datetime = '2009-02-15 14:63';  // invalid time
        $date = chk_MySQL_Datetime($format, $datetime);
        echo "Format: $format; datetime is " . ($date ? 'valid' : 'invalid' ) . " Expected $datetime is " . $fmtdatetime . "<br>";
//echo output = Format: Y-m-d H:i; datetime is invalid Expected 2009-02-15 14:63 is 2009-02-15 15:03

        $result = insert_in_table($datetime);
        echo $result . "<br>";
 //echo output = Inserted datetime = 2009-02-15 14:63, MySQL stored 0000-00-00 00:00:00, fmtdatetime = 2009-02-15 15:03

        $datetime = 'x-02-15 14:59';  // invalid time
        $date = chk_MySQL_Datetime($format, $datetime);
        echo "Format: $format; datetime is " . ($date ? 'valid' : 'invalid' ) . " Expected $datetime is " . $fmtdatetime . "<br>";
 //echo output = Format: Y-m-d H:i; datetime is invalid Expected x-02-15 14:59 is 2009-02-15 15:03

        $result = insert_in_table($datetime);
        echo $result . "<br>";
//echo output =  Inserted datetime = x-02-15 14:59, MySQL stored 0000-00-00 00:00:00, fmtdatetime = 2009-02-15 15:03
?>

答案 9 :(得分:0)

也许您必须使用BLACKHOLE引擎创建数据库,阅读here。并检查PDOException抛出的异常。

$dbh = new PDO('mysql:host=localhost;dbname=test', 'username', 'p@s5W0Rd!!!', array(PDO::ATTR_PERSISTENT => true));

// CREATE DATABASE test;
// CREATE TABLE test.foo ( bar DATETIME ) ENGINE=BLACKHOLE;

try {
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $dbh->beginTransaction();

    $dateTime = new DateTime();
    $dateTime = $dateTime->format('c');
    $dbh->exec("INSERT INTO foo (bar) VALUES ('".$dateTime."')");
    $dbh->commit();
} catch (PDOException $e) {
    $errorInfo = $dbh->errorInfo();

    if ($e->getCode() === '22007'
        and $dbh->errorCode() === '22007'
        and $errorInfo[0] === '22007'
        and preg_match('/^incorrect datetime/', strtolower($errorInfo[2])) === 1) {

        throw new Exception($errorInfo[2], (int) $e->getCode());
    }
}

答案 10 :(得分:0)

DATETIME - 在SQL

SELECT your_unreliable_datetime_column, CAST(your_unreliable_datetime_column as DATETIME)
FROM some_cool_table
WHERE
CAST(your_unreliable_datetime_column as DATETIME) IS NOT NULL
AND
your_unreliable_datetime_column = CAST(your_unreliable_datetime_column as DATETIME)

这应该只选择有效的DATETIME 也应该适用于DATETIME相应 ,但未经过测试...

我没有找到关于转换失败的CAST()返回值的任何文档,但documentation covers a special case - 可能失败 - 返回NULL

  

将“零”日期字符串转换为日期CONVERT()CAST()   返回NULL并在NO_ZERO_DATE SQL模式时生成警告   启用。

此外,根据我的测试,似乎 CAST()任何转换失败时表现相同 - 返回NULL并生成警告。

我实际上是在MariaDB 10.0.30

上对此进行了测试

答案 11 :(得分:0)

检查值是否是您可以使用的日期 day(dateToCheck) = 0

答案 12 :(得分:0)

尝试使用此... WHERE DATE_FORMAT(DATE('$ value'),'%Y-%m-%d')='$ value'

使用Perl时,如果失败,$ sth->行将返回零

如果$ sth->行成功,它将返回非零值