How to format Date & Time input from a php form into MySQL UNIX datetime format

If you’re building any type of app that requires dates and times you’ll need to know how to convert user entered data into the MySQL datetime format.

The datetime format is: yyyy/mm/dd hh:mm:ss

Note that the time portion is 24hr time and not 12 hour time.

This function will output a MySQL datetime formatted string (Note the use of the ‘G’ as the letter for the hour, this tells the date function to output 24hr time:

$mysql_date = date(‘Y-m-d G:i:s’,strtotime($somedate.’ ‘.$sometime.’ ‘.$am_or_pm));

To get this data from a form try this code:

<?php //Check to see if a date has been posted
$mysql_date = date(‘Y-m-d G:i:s’,strtotime($_POST[‘Date’].’ ‘.$_POST[‘Time’].’ ‘.$_POST[‘ampm’]));
<?php //Display the MySQL datetime if it exists
if (isset($mysql_date)){ ?>
<br/>The MySQL datetime version is: <?php echo ($mysql_date); ?>
<?php } ?>
<form id=”form1″ name=”form1″ method=”post” action=””>
<input name=”Date” type=”text” id=”Date” value=”10/23/2010″ />
<input name=”Time” type=”text” id=”Time” value=”12:00:00″ />
<input name=”ampm” type=”radio” id=”ampm” value=”am” checked=”checked” />
<input type=”radio” name=”ampm” id=”ampm” value=”pm” />
<input type=”submit” name=”Submit” id=”Submit” value=”Submit” />

An actual application will require additional coding, but this shows a simple way to format user entered date and time values into MySQL Unix datetime format.

DLL Written by: Don Lyckman
Don Lyckman is a Web Developer/Designer

If you enjoyed this post, please consider leaving a comment or subscribe to the feed and get future articles delivered to your feed reader.


3 Responses to “How to format Date & Time input from a php form into MySQL UNIX datetime format”

Leave Comment