Reputation: 523
I am use PHP and MySQL. How can I convert time with format HH:MM AM/PM to HH:MM:SS to save time to MySQL?
Upvotes: 0
Views: 6584
Reputation: 26066
Easy. In MySQL use DATE_FORMAT
like this:
SELECT DATE_FORMAT(NOW(), '%H:%i:%s');
And using your example you could couple this with STR_TO_DATE
like this:
SELECT DATE_FORMAT(STR_TO_DATE('09:41 AM', '%h:%i %p'), '%H:%i:%s');
Then in your MySQL query you could substitute the 09:41 AM
with a variable based on your MySQL table.
Upvotes: 0
Reputation:
Use date_format() to resolve your problem:
DATE_FORMAT(date,'%H:%i:%s')
Upvotes: 0
Reputation: 555
The way I would do it is:
<?php
$date = "6:23 AM";
$timeType = explode(" ", $date);
$timeItems = explode(":", $timeType[0]);
if($timeType[1] == "PM"){
$timeItems[0] += 12;
}
$time = implode(":", $timeItems);
$time .= ":00";
var_dump($time);
?>
Upvotes: 1
Reputation: 19308
Use strtotime
to convert it to a timestamp and then format that using the date
function.
Example below assumes $time
has been set to the time you need to format.
$time = date( "H:i:s", strtotime( $time ) );
Upvotes: 2