Search code examples
phpmysqltimefetchtypeconverter

Get time from a varchar(100) type with (HH:MM AM/PM) format


How to convert the string ("RD/OT 07:30") to time. I just know how to convert ("07:30 AM") to time. This code below is giving me a blank data.

 $id = strtoupper($_POST['id']);
    $query = mysql_query("SELECT STR_TO_DATE('RD/OT 07:30','%x %h:%i')  as ScheduleIn  FROM tbl_uploadedschedule") or die(mysql_error());
    $res =   mysql_fetch_assoc($query);
    $r = $res['ScheduleIn'];
    return($r);

Solution

  • You can use STR_TO_DATE(str,format) function to convert time format:

    SELECT STR_TO_DATE(`field_name`, '%h:%i %p')
    FROM `table_name`
    # this will convert '7:30 AM' to '07:30:00'
    

    If whole DATETIME format is outputed, you can use TIME(expr) function to get only TIME part.

    Demo (don't know why sqlfiddle is ignoring TIME() function; it works on localhost).