简体   繁体   中英

Convert MySQL time to standard time with AM and PM

Having trouble converting AM time values from MySQL fetch_array when using the PHP date() function. Not sure why the stop time below is being printed as the 7:00PM when it should be 11:00AM. Any ideas? Any help is much appreciated!

<?php
$mysql_output = array('start' => '19:00:00','stop' => '11:00:00');

$start_time = date('g:iA',$mysql_output['start']);
$stop_time = date('g:iA',$mysql_output['stop']);

echo "<p>start_time: $start_time</p>";
echo "<p>stop_time: $stop_time</p>";
?>

The result doesn't convert the AM time correctly; should read 11:00AM for stop_time :

start_time: 7:00PM
stop_time: 7:00PM

The date() function takes a Unix timestamp, not a string datetimestamp. You need to put a MySQL datetimestamp through strtotime() first.

$start_time = date('g:iA', strtotime($mysql_output['start']));
$stop_time = date('g:iA', strtotime($mysql_output['stop']));

If you want mysql to convert it for you, just use the DATE_FORMAT( ) function.

SQLFiddle Demo

The date function is misinterpreting your data.

You should create a time object first, then pass that in as a parameter to date.

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