且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将 AM PM 时间字符串存储到 MySQL 中的 TIME 数据类型并在显示时使用 AM PM 检索?

更新时间:2023-10-22 14:32:40

插入:

# replace first argument of STR_TO_DATE with value from PHP/frontend
TIME( STR_TO_DATE( '10:00 PM', '%h:%i %p' ) );

选择:

# replace first argument with your time field
TIME_FORMAT( '22:00:00', '%h:%i %p' );


我会继续假设您使用 mysql lib 函数.


I'll just go ahead and presume you use mysql lib functions.

// first sanitize the $_POST input
// also, make sure you use quotes to identify the $_POST keys
$open = mysql_real_escape_string( $_POST[ 'MondayOpen' ] );
$close = mysql_real_escape_string( $_POST[ 'MondayClose' ] );

// this is the query, which should work just fine.
$sql = '
    INSERT INTO
        `table_lib_hours`
    SET
        `day_name` = "Monday",
        `day_open_time` = TIME( STR_TO_DATE( "' . $open . '", "%h:%i %p" ) ),
        `day_close_time` = TIME( STR_TO_DATE( "' . $close . '", "%h:%i %p" ) )
    ';

$result = mysql_query( $sql );

然后检索值:

$sql = '
    SELECT
        `day_open_time`,
        `day_close_time`,
        TIME_FORMAT( `day_open_time`, "%h:%i %p" ) as day_open_time_formatted,
        TIME_FORMAT( `day_close_time`, "%h:%i %p" ) as day_close_time_formatted
    FROM
        `table_lib_hours`
    WHERE
        `day_name` = "Monday"
    ';

$resultset = mysql_query( $sql );

这将返回一个结果集,其中格式化数据位于 *_formatted 字段

This will return a result set where the formatted data is in the *_formatted fields


%m(月)调整为 %i(分钟).感谢 Donny 发现明显的失误.


Adjusted %m (month) to %i (minutes). A thank you to Donny for the well spotted slip up.