0

I have dates stored in a MySQL database like so: 2012-02-10

When i output them using PHP, is there a function I can use that will output it like so 10/02/2012

Ive tried:

$theDate = date_format($row['date'], 'd/m/Y');
echo $theDate;

but it doesnt seem to work. Any help appretiated.

PHP Version 5.3.3

0

4 Answers 4

3

You need to use date_create() before using date_format(). This is because date_format() expects a DateTime object as the first parameter.

$date = date_create($row['date']);
echo date_format($date, 'd/m/Y');

Another way to do the same thing:

$dt = new DateTime('2012-02-10');
echo $dt->format('d/m/Y');

For the PHP 5.4 users out there it can be simplified to:

echo (new DateTime('2012-02-10'))->format('d/m/Y');

edit

To comment on the alternative solutions provided, they can be simplified to:

echo date('d/m/Y', strtotime($row['date']));

Just keep in mind that they do not account for daylight savings time or timezones like DateTime does.

Sign up to request clarification or add additional context in comments.

1 Comment

Class member access on instantiation has been added in 5.4 version, not 5.5.
1

Here's a really simple way to do it

<?php
    $theDate = $row['date'];
    echo date("m/d/Y", strtotime($theDate));
?>

Comments

0

The old way (non-OOP) to do it,

$t = strtotime('2012-02-10');
echo date('d/m/Y', $t);

Functions to check: strtotime, date

1 Comment

Like the old way tag ;-)
0

Here are a few examples:

$input = '2012-02-10';

// datetime (object oriented style)
$dt = new DateTime($input);
echo $dt->format('d/m/Y') . "\n";

// datetime (procedural style)
$dt = date_create($input);
echo date_format($dt, 'd/m/Y') . "\n";

// strtotime
$m = strtotime($input);
echo date('d/m/Y', $m) . "\n";

// substr
echo substr($input,8,2) . "/" . substr($input,5,2) . "/" . substr($input,0,4) . "\n";

// explode
$m = explode('-', $input);
echo "$m[2]/$m[1]/$m[0]" . "\n";

// preg_match
preg_match('~^(\d+)-(\d+)-(\d+)$~', $input, $m);
echo "$m[3]/$m[2]/$m[1]" . "\n";

// sscanf
$m = sscanf($input, '%d-%d-%d');
echo "$m[2]/$m[1]/$m[0]" . "\n";

p.s. did I miss any? ;)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.