MySql database excludes A.M, P.M, from datetime, timestamp, time, PHP, SQL

爱⌒轻易说出口 提交于 2020-01-25 18:10:07

问题


I have three data types in my database. Datetime, timestamp, and time. I get the time using the date function and tried to insert it into the database under all three columns, but all three columns rejected the A.M, P.M part of the date function. I don't understand why. I need the A.M, P.M part of the date function to be also inserted, so I can sort the data in my database more efficiently by time. Is there another column that can store the A.M, P.M part of the date, or is there a workaround this? Thanks.

$time = date('h:i:s A');
//insert $time into all three columns into the database

回答1:


The workaround is to use the hours value as 24 hour clock. To represent '3:45:56 PM', insert to the database column a string value '15:45:56'.

Otherwise, you can use the STR_TO_DATE function to convert the string into a valid TIME value.

 INSERT INTO mytable (mycol) VALUES (STR_TO_DATE('3:45:56 PM','%h:%i:%s %p'))

To retrieve a TIME value from a database column, formatted as 12 hour clock with AM/PM.

SELECT DATE_FORMAT(mytimecol,'%h:%i:%s %p') AS mytimestr FROM ... 

References:

STR_TO_DATE https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_str-to-date

DATE_FORMAT https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format




回答2:


Change the column data type as Varchar(20) and insert $time = date('h:i:s A'); into database.

Get from DB:-

while fetching this column from database u can use date('h:i:s A',strtotime($fetched_datetime_from_db)).

Enjoy!!



来源:https://stackoverflow.com/questions/31549767/mysql-database-excludes-a-m-p-m-from-datetime-timestamp-time-php-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!