michaelmcgurk
michaelmcgurk

Reputation: 6509

Re-Format Date with PHP

I have the following value in a variable: 26/03/2011

I'd like to get this in the format: 2011-03-26

How do I achieve this?

Many thanks

Upvotes: 1

Views: 128

Answers (3)

Matthew
Matthew

Reputation: 48284

While there are many ways to do this, I think the easiest to understand and apply to all date conversions is:

$date = date_create_from_format('d/n/Y', $date)->format('Y-n-d');

It is explicit and you'll never have to wonder about m/d or d/m, etc.

Upvotes: 3

tplaner
tplaner

Reputation: 8461

Might be a good idea to use the date() function combined with mktime():

$date = explode('/', '26/03/2011');

echo date('Y-m-d', mktime(0,0,0,$date[1],$date[0],$date[2]));

The reason why this could be a good idea is if you ever want to format the date in a different (more complex) format, say "March 26th, 2011" you could just do:

$date = explode('/', '26/03/2011');

echo date('F jS, Y', mktime(0,0,0,$date[1],$date[0],$date[2]));

Upvotes: 0

Mārtiņš Briedis
Mārtiņš Briedis

Reputation: 17752

Try this:

list($d, $m, $y) = explode("/", "26/03/2011");
echo "$y-$m-$d";

Upvotes: 4

Related Questions