简体   繁体   中英

How to input time from <select> into mysql and have it output am/pm?

Hey guys so, im doing this form with a input that will contain the time and i want to make it so that when users choose the time (for example 8:30 AM), it will be stored in mysql, and will be output by php with the exact time (8:30 AM).

Here is the form. A simple select button with increments of 30 on the time.

http://jsfiddle.net/jXVPS/

The main problem is i dont know how mysql will recognize if it is AM/PM?

What values i should put for the select fields, how i would insert it into the mysql database, and have mysql or php recognize wheather it is 1:00 AM or 1:00 PM. Is there some sort of 24 hour clock in mysql that makes it recognize wheather or not it is AM/PM?

Use TIME column type :

TIME

A time. The range is '-838:59:59' to '838:59:59'. MySQL displays TIME values in 'HH:MM:SS' format, but allows you to assign values to TIME columns using either strings or numbers.

It will parse the values in your select options nicely.


Edit : Example of use:

// saving in the db
$sql = "
  INSERT INTO table_name SET
  # ...
  name_of_the_time_column = '" . mysql_real_escape_string($_POST['start_time']) . "'";

// retrieving from the db
$sql = "
  SELECT id, ..., TIME_FORMAT(name_of_the_time_column, '%h:%i:%s %p') AS formatted_time
  FROM table_name
  # ...
  ";

Not tested :

INSERT INTO myTable
SET time = TIME(STR_TO_DATE('8:30:00 AM','%h:%m:%s %p'))

Here's MySQL's time/date stuff. I think the TIME type would be best for you since you don't need a date, and the format you've got for your values should fit well. I think you can just put them as strings exactly like that.

http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-types.html

After you submit thru form submission or ajax and your responding PHP page takes over, perform a query with the following string in the PHP:
"INSERT INTO table (userId, time, ...) VALUES (..., '$inTime', ...)"

And then echo it out since you want the next page to repeat it.


Response to comment

I figure you mean that wou want 13:00:00 to be 1:00 PM when you echo it out later right?

Theres probably something you can do with time functions for either PHP or MySQL (PHP below, MySQL above), but I don't know from memory and this is simple enough you can just do it on your own. http://www.php.net/manual/en/ref.datetime.php

$time = //get time field from MySQL
list($h, $m, $s) = explode($time, ':');
if ($h > 12) {$h -= 12; $amOrPm = 'PM'}; else {$amOrPm = 'AM';}
if ($h == 0) {$h = 12;}

echo "$h:$m $amOrPm";

PS - 13:00:00 is 1pm, not am.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM