简体   繁体   中英

convert date/time from 24-hour format to 12-hour AM/PM using select query in php/Mysql

Displaying Time and date in 12hour format using mysql select query in php.

DB Name Demo

Table name student

DB Structure

Id      firstname    lastname      pubdate
int(11) varchar(100) varchar(100)  timestamp

I have inserted 5 records in student table and displayed using select query everything works great but i am unable to display pubdate in proper 12 hour format!

please can somebody help me out in acheiving it Thanks!

Code

$sql = "select id,firstname,lastname,pubdate from student";
$results = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($results))
{
   echo $row['id'];
   echo $row['firstname'];
   echo $row['lastname'];
   echo $row['pubdate'];

}

use MySQL DATE_FORMAT

DATE_FORMAT(pubdate,'%Y-%m-%d %h:%i %p')

You query like that :-

$sql = "select id,firstname,lastname,
DATE_FORMAT(pubdate,'%Y-%m-%d %h:%i %p') as pubdate from student";

i think you can use :

echo date('Y-m-d h:i:s', strtotime($row['pubdate']));

Live Sample

h is used for 12 digit time
i stands for minutes
s seconds
a will return am or pm (use in uppercase for AM PM)
m is used for months with digits
d is used for days in digit
Y uppercase is used for 4 digit year (use it lowercase for two digit)

要将日期转换为上午12点,请使用

echo date('h:i:s a m/d/Y', strtotime($row['pubdate']));

Use date() and strtotime() of PHP:

echo date("Y-m-d h:i:s A", strtotime($row["pubdate"])); /* WILL ECHO 2015-11-10 02:50:24 PM */

Refer here for more date format.

使用date()和strtotime()函数

echo date("Y-m-d h:i:s A", strtotime($row["pubdate"])); 

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