Thursday, September 12, 2013

PHP, verify input date format


MySQL DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD HH:MM:SS'.

How to verify date input format is  'YYYY-MM-DD HH:MM:SS', i.e."Y-m-d H:i:s"  in PHP?

Method 1:

function checkDateTime($data) {
    if (date('Y-m-d H:i:s', strtotime($data)) == $data) {
        return true;
    } else {
        return false;
    }
}


Method 2:

function validateDate($date, $format = 'Y-m-d H:i:s')
{
   
$d = DateTime::createFromFormat($format, $date);
    return
$d && $d->format($format) == $date;
}

Mote detail: create a table edu_tests in mysql using datetime format
CREATE TABLE  edu_tests (
  `test_id` mediumint(8) unsigned NOT NULL auto_increment,
  `course_id` mediumint(8) unsigned NOT NULL default '0',
  `title` varchar(100) NOT NULL default '',
  `format` tinyint(4) NOT NULL default '0',
`start_date` datetime NOT NULL default '0000-00-00 00:00:00',
  `end_date` datetime NOT NULL default '0000-00-00 00:00:00',
    primary key (test_id)
  ) 


 Example PHP code to  verify input date format with the same format as MYSQL datetime format:
<html>
    <h1>PHP, verify input date format</h1>
    <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
      <label for="release">Release Date </label><br />
      <input name="date" id="date" type="text" size="40"
      value="<?php if(!isset($_POST['date']))
      echo date("Y-m-d H:i:s");
      else echo $_POST['date'];?>" /><br>
   <input type="submit" name="submit" value="Submit Form"><br>
    </form>
<?php
function checkDateTime($data) {
    if (date('Y-m-d H:i:s', strtotime($data)) == $data) {
        return true;
    } else {
        return false;
    }
}   
if(isset($_POST['submit']))
{
    if(!checkDateTime($_POST['date']))
     echo '<h2>Input date format is wrong.</h2>';
    else echo '<h2>Input date format is <i>correct.</i></h2>';
}
?>
</html> 

No comments:

Post a Comment