Change date from YYYY-MM-DD to DD-MM-YYYY

I’m new here so I hope I’ve posted this in the right place.
I’ve recently started doing some coding, I’ve been putting together a table that’s getting data from a database and displaying it within the table.
One of the pieces of information I’m getting from the database is a date of birth. The date displays fine but it is displaying year-month-day. I would like it to display it day-month-year.

How do I do this? I’ve been told its quite awkward as there are so many different ways in which you can display a date.

Here’s my code, thanks.

echo ‘

’;
echo ‘’;
echo ‘’;
echo ‘’;
echo ‘’;
echo ‘
Date of Birth:’. $row[‘dob’] .’
’;

I prefer working with proper datetime objects, which you can just output with whatever format you like. You could create the datetime object using ‘dob’ before echoing it, or you could just create it and echo the format in one go.

[php]echo ‘

’;
echo ‘’;
echo ‘’;
echo ‘’;
echo ‘’;
echo ‘
Date of Birth:’. (new DateTime($row[‘dob’]))->format(‘d-m-Y’) .’
’;[/php]

[php]$dob = new DateTime($row[‘dob’]);

echo ‘

’;
echo ‘’;
echo ‘’;
echo ‘’;
echo ‘’;
echo ‘
Date of Birth:’. $dob->format(‘d-m-Y’) .’
’;[/php]

And I’d suggest to stop echoing HTML, it confuses a lot of editors and it simply looks cleaner to not do it

[php]$dob = new DateTime($row[‘dob’]);
?>

Date of Birth: <?= $dob->format('d-m-Y') ?>
[/php]

Excellent, thanks ;D

Why not let the database do the work for you?

[php]SELECT date_format(dob, ‘%m/%d/%Y’) AS dob, FROM your_table[/php]

I usually do it this way when it’s strictly used for output.

Sponsor our Newsletter | Privacy Policy | Terms of Service