Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate a MYSQL Date in PHP?

Tags:

date

php

mysql

Users would select their date from 3 dropdowns (day, month, year). I will combine them on server-side to make a string like '2008-12-30'. How can I then validate to make sure this date was in the right format/numeric only, etc?

like image 964
Ali Avatar asked Feb 28 '09 03:02

Ali


People also ask

How do you check whether a date is valid or not in PHP?

The checkdate() function is used to validate a Gregorian date.

How do you validate a date?

The date validator requires day, month and year. If you are looking for hour and time validator, HH:mm , for example, you should use the regexp validator. Below are some example of possible formats: YYYY/DD/MM.

Is date function in MySQL?

MySQL date/time Functions. The date() function is used to get the date from given date/datetime. The adddata() function is used to get the date in which some time/date intervals are added. The curdate() function is used to get the current date.


2 Answers

I am using this function:

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

// check it: 
  $a = validateMysqlDate('2012-12-09 09:04:00');
  $b = validateMysqlDate('20122-12-09 09:04:00');
  $c = validateMysqlDate('2012-12_09 09:04:00');
  $d = validateMysqlDate('');
  var_dump( $a );
  var_dump( $b );
  var_dump( $c );
  var_dump( $d ); 
?>

$a is true, the others are false - and that is correct

The function from Raveren (above) will not cover valid dates with timestamps !!! $a returns false there! And btw: checkdate() would return true for $b although it is not a valid mysql datetime

like image 26
sebilasse Avatar answered Oct 26 '22 23:10

sebilasse


I personally found this to be the correct and elegant way to determine if the date is both according to format and valid:

  • treats dates like 20111-03-21 as invalid - unlike checkdate()
  • no possible PHP warnings (if any one parameter is provided, naturally) - unlike most explode() solutions
  • takes leap years into account unlike regex-only solutions
  • fully compatible with the mysql DATE format (10.03.21 is the same as 2010-03-21)

Here's the method you can use:

/**
 * Tests if a string is a valid mysql date.
 *
 * @param   string   date to check
 * @return  boolean
 */
function validateMysqlDate( $date )
{
    return preg_match( '#^(?P<year>\d{2}|\d{4})([- /.])(?P<month>\d{1,2})\2(?P<day>\d{1,2})$#', $date, $matches )
           && checkdate($matches['month'],$matches['day'],$matches['year']);
}
like image 142
raveren Avatar answered Oct 26 '22 23:10

raveren