[英]How to output day of week from MySQL date
我無法找到或弄清楚如何輸出MySQL日期字段作為縮短的星期幾。
我不確定是在MySQL還是PHP中執行此操作。
理想情況下,我想使用PHP函數執行此操作,但為了使事情復雜化,我想要輸出為星期幾的日期字段通過while循環運行到表中。 這讓我覺得我需要在MySQL中做到這一點。
基本上,我希望能夠使用PHP的mktime()或MySQL的DAYOFWEEK()之類的東西,除非我需要能夠在while循環中執行此操作,我需要能夠使用變量或列名稱功能而不必輸入或拉出一個特定的格式日期。
任何幫助是極大的贊賞!
PS我在下面添加了數據當前來自數據庫的方式。 ###是我遇到麻煩的地方; 這是我需要使用'e_date'列回顯Day的地方。 (下一個Date也使用'e_date'列。)
// Get all the data from the "events" table
$result = mysql_query("
SELECT *
FROM events
WHERE e_type != '' && e_date >= CURDATE() && e_date <= (CURDATE() + 15)
ORDER BY e_date,e_ampm,e_time")
or die(mysql_error());
echo "<table border='1' style=\"border:none;font-size:12px;\">";
echo "<tr> <th>Day</th> <th>Date</th> <th>Time</th> <th>Type</th> <th>Description</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
###
echo "</td><td>";
echo $row['e_date'];
echo "</td><td>";
echo $row['e_time'];
echo $row['e_ampm'];
echo "</td><td>";
echo $row['e_type'];
echo "</td><td>";
echo $row['e_name'];
echo "</td></tr>";
}
echo "</table>";
試試這個修改過的版本 您可以使用DATE_FORMAT,使用datefield作為輸入變量,%a表示輸出的格式。 %a告訴DATE_FORMAT返回日期的縮寫日期。 試一試,看看它是否有效,我有一段時間沒用過MySQL,所以我錯了。
// Get all the data from the "events" table
$result = mysql_query("
SELECT DATE_FORMAT(e_date, '%a') as day, e_date, e_time, e_ampm, e_type,e_name
FROM events
WHERE e_type != '' && e_date >= CURDATE() && e_date <= (CURDATE() + 15)
ORDER BY e_date,e_ampm,e_time")
or die(mysql_error());
echo "<table border='1' style=\"border:none;font-size:12px;\">";
echo "<tr> <th>Day</th> <th>Date</th> <th>Time</th> <th>Type</th> <th>Description</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['day'];
echo "</td><td>";
echo $row['e_date'];
echo "</td><td>";
echo $row['e_time'];
echo $row['e_ampm'];
echo "</td><td>";
echo $row['e_type'];
echo "</td><td>";
echo $row['e_name'];
echo "</td></tr>";
}
echo "</table>";
我會保持數據庫部分處理數據,並向PHP呈現。 您希望使用strftime()
或strptime()
具體取決於您的數據來自MySQL。
我的建議是始終以unixtime格式處理日期。 我總是將日期存儲為數據庫中的整數字段。
對於您的情況,您可以通過將日期字段轉換為unixtime來查詢日期字段,並讓php日期函數來處理格式化。
<?php
$query = "
SELECT UNIX_TIMESTAMP(e_date) AS UNIXTIME, *
FROM events
WHERE e_type != '' && e_date >= CURDATE() && e_date <= (CURDATE() + 15)
ORDER BY e_date,e_ampm,e_time";
$result = mysql_query($query) or die("error");
...
while($row = mysql_fetch_array( $result ))
{
echo "<tr>";
echo sprintf('<td>%s</td>', date('l', $row["UNIXTIME"])); //day of week
...
echo "</tr>";
}
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.