2015-11-10 37 views
0

使用mysql在php中選擇查詢以12小時格式顯示時間和日期。使用php/Mysql中的select查詢將日期/時間從24小時格式轉換爲12小時上午/下午

DB名稱演示

表名學生

DB結構

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

我已經插入5個記錄在學生的表並顯示使用select查詢一切都很正常 但我無法以適當的12小時格式顯示pubdate!

請有人幫我出來 實現它謝謝!

代碼

$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']; 

} 

回答

1

迄今爲止換算成12小時AM/PM使用

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

使用MySQL的DATE_FORMAT

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

您查詢這樣的: -

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

謝謝@Rahautos。 – Sjay

+0

這是我的榮幸:) - @Sjay –

+0

如果我的答案可以幫助你,請接受我的回答@Sjay –

1

使用date()和PHP的strtotime()

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

參考here更多的日期格式。

+0

謝謝@Logan Wayne – Sjay

2

我認爲你可以使用:

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

現場樣品

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) 
+0

謝謝@穆罕默德·阿爾斯蘭 – Sjay

1

使用日期()和的strtotime()函數

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