Вы находитесь на странице: 1из 2

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

Posted at September 24, 2010 by: DLL


If youre building any type of app that requires dates and times youll 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


if(isset($_POST[Date])){
$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=>
<p>
<label>Date
<input name=Date type=text id=Date value=10/23/2010 />
</label>

</p>
<p>
<label>Time
<input name=Time type=text id=Time value=12:00:00 />
</label>
<label>
<input name=ampm type=radio id=ampm value=am
checked=checked />
am</label>
<label>
<input type=radio name=ampm id=ampm value=pm />
pm</label>
</p>
<p>
<label>
<input type=submit name=Submit id=Submit value=Submit />
</label>
</p>
</form>
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.

Вам также может понравиться