Thursday, May 7, 2009

Formatting PHP dates

Okay, why hasn't anyone put this in examples on the web yet?

You're building a search form for users. And you want them to enter a date that they want to search. I want to search for events that occur on July 21 this year, so I'll enter 7/21/2009 into the search box.

BUT...your database has the record stored as 2009-07-21, so you need to make a conversion.

Enter the explode command. And such a wonderful command it is. But php.net's own site documenting it doesn't even make mention that you can convert dates with it. How absurd is that? For all the php hacks like myself, here's how it's done.

$date = $_POST['dateentry']; // You should probably addslashes, but we're just playing here
$exploding=explode('/',$date);
$reformatted=$exploding[2]."-".$exploding[0]."-".$exploding[1];
echo "$reformatted"; // Returns "2009-07-21"

Come on, internet! Are you really going to make me figure these things out myself?

2 comments:

Dave said...

"Sexploding"

'nuff said....

Unknown said...

I can't believe I missed that piece of awesomeness when I was writing this. It was entirely unintentional, but I'm using the $explode variable name from now on. Bonus for whatever poor soul earns the task of taking over my code maintenance when I get a new job.