Aymn Alaney
Aymn Alaney

Reputation: 523

Convert time with format HH:MM AM/PM to HH:MM:SS

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

Answers (4)

Giacomo1968
Giacomo1968

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

user3522371
user3522371

Reputation:

Use date_format() to resolve your problem:

DATE_FORMAT(date,'%H:%i:%s')

Upvotes: 0

James McClelland
James McClelland

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

Nathan Dawson
Nathan Dawson

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

Related Questions