Converting mysql TIME from 24 HR to AM/PM format

后端 未结 5 538
南旧
南旧 2020-12-17 14:37

I want to display the TIME field from my mysql table on my website, but rather than showing 21:00:00 etc I want to show 8:00 PM. I need a function/code to do this or even an

5条回答
  •  星月不相逢
    2020-12-17 15:37

    You can also select the column as a unix timestamp using MYSQL's UNIX_TIMESTAMP() function. Then format it in PHP. IMO this is more flexible...

    select a, b, c, UNIX_TIMESTAMP(instime) as unixtime;
    

    The in PHP use the date() function & format it any way you want.

    unixtime); ?>
    

    The reason I like this method as opposed to formatting it in SQL is b/c, to me, the date's format is a display decision & (in my opinion) formatting the date in SQL feels wrong... why put display logic in your SQL?

    Now - if you're not processing the data in PHP and are doing adhoc queries then DATE_FORMAT() is the way to go. But if you're gonna have the data show up on the web I'd go with UNIX_TIMESTAMP() and do the formatting in PHP...

    I mean... lets say you want to change how the date & time are displayed on the page... wouldn't it feel "off" to have to modify your SQL for a display tweak?

    my 2 cents

提交回复
热议问题