[PHP - MySQL] Date conversion code

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
cheeney
Forum Newbie
Posts: 1
Joined: Thu Jun 25, 2009 10:15 am

[PHP - MySQL] Date conversion code

Post by cheeney »

Hi

I'm hoping for a little help here.

I'm writing a very simple database app (using MySQL). I need the PHP code to be able to take a date like 25/6/09 and convert it into whatever format is needed by MySQL.

This is where I need the help. I've looked around a bit and have found stuff that will handle 25/06/2009 but I'd like the code to be more forgiving. Unfortunately, I've found no suitable examples. :(


Any help/links/code is greatly appreciated.


Thanks in advance
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: [PHP - MySQL] Date conversion code

Post by pickle »

I think you'll need to explode it, rebuild it into a timestamp, then use the MySQL function FROM_UNIXTIME() to convert it to a MySQL date stamp:

Code: Select all

$raw = '26/5/09';
list($day,$month,$year) = explode('/',$raw);
$stamp = mktime(0,0,0,$month,$day,'20'."$year");//treat $year as a string to prevent the leading zero from getting stripped
$query = 'INSERT INTO `myTable` (`dateField`) VALUES (FROM_UNIXTIME('.$stamp.'))';
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply