0

How Can I Change date format of Fetched row / data

My code displays date in Y-m-d format, i want to change format in d-m-Y.

My Code is:

$connect = new PDO('mysql:host=localhost;dbname=comment', 'root', '12345678');

$query = "
SELECT * FROM tbl_comment 
WHERE parent_comment_id = '0' 
ORDER BY comment_id DESC
";

$statement = $connect->prepare($query);

$statement->execute();

$result = $statement->fetchAll();
$output = '';
foreach($result as $row)
{
 $output .= '
 <div class="panel panel-default">
  <div class="panel-heading">By <b>'.$row["comment_sender_name"].'</b> on <i>'.$row["date"].'</i></div>
  <div class="panel-body">'.$row["comment"].'</div>
  <div class="panel-footer" align="right"><button type="button" class="btn btn-default reply" id="'.$row["comment_id"].'">Reply</button></div>
 </div>
 ';
 $output .= get_reply_comment($connect, $row["comment_id"]);
}

echo $output;

  • Does this answer your question? [Convert a date format in PHP](https://stackoverflow.com/questions/2487921/convert-a-date-format-in-php) – Rain Dec 05 '19 at 12:36

4 Answers4

0

You can save the date in variable and use date_format(),

$date = date_create(($row['date']));;
$formatted_date = date_format($date,"d/m/y");

Then echo $formatted_date where you want.

Ahmed Ali
  • 1,908
  • 14
  • 28
0
$date = date_create(($row['date'])); 
$publishDate = date_format($date,"d-m-Y");
sathish k
  • 39
  • 4
0

Change $row["date"] for date('d-m-Y', strtotime($row["date"]))

You could assign the database value to a variable first, but it's unnecessary overhead.

Another alternative is to use PHP's built-in date_format function, but you'd first need to create a date object from the database value which, again, is unnecessary overhead if you just need to display the date in a different format

Javier Larroulet
  • 3,047
  • 3
  • 13
  • 30
0

Hi you need to execute the following query

SELECT *, date_format(`date`,'%d-%m-%Y') as `comment_date` FROM tbl_comment' WHERE parent_comment_id = '0' ORDER BY comment_id DESC;

Then use it with the aliasing name(i.e. comment_date) inside php loop.

Udit
  • 129
  • 2
  • 6