简体   繁体   中英

Format date from database to table using php

I have a database full of football fixtures, sorted in descending order. Everything works fine however the dates are in the following format: YYYYMMDD like so - 2014-05-11.

All table contents are selected with:

 $result = mysqli_query($con,"SELECT * FROM Fixtures ORDER BY Date DESC");

Then inserted into the table with the below code:

while($row = mysqli_fetch_array($result))
  {

  echo "<tr>";
  echo "<td>" . $row['Date'] . "</td>";
  echo "<td>" . $row['Home Team'] . "</td>";
  echo "<td>" . $row['Score'] . "</td>";
  echo "<td>" . $row['Away Team'] . "</td>";
  echo "<td>" . $row['Score1'] . "</td>";
  echo "<td>" . $row['Competition'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

How can I make it so these dates appear DDMMYYYY such as 11-05-2014?

Thanks!

Solution:

echo "<td>" . date('d-m-Y', strtotime($row['Date'])) . "</td>";

Manual

Use DateTime::createFromFormat

$date = DateTime::createFromFormat('dmY', $row['Date']);
echo $date->format('d-m-Y');

Either fetch it properly from the database:

$query = "SELECT
    ...,
    ...,
    DATE_FORMAT(Date, '%d-%m-%Y') AS Date
FROM Fixtures
ORDER BY Date DESC";

$result = mysqli_query($con, $sql);

Or format it in your PHP

echo date('d-m-Y', $row['Date']);

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