tags:

views:

67

answers:

2

Hi guys my application parses text files where date values are stored in the format: DDMMMYYYY eg: 12MAR2009.

I noticed that inserting this value as it is into a database datetime value doesn't work at all. How do I convert this into a datetime value which can be entered into a database. My application is in php.

+2  A: 
$timestamp = strtotime("12MAR2009");

...

INSERT INTO my_table (..., timestamp) VALUES (..., FROM_UNIXTIME($timestamp))

The PHP function strtotime() will take almost any string containing a date/time value, and convert it to a unix timestamp.

The MySQL function FROM_UNIXTIME() will take a unix timestamp and convert it to MySQL's datetime format.

Amber
+3  A: 

Something like this should convert your date into MySQL's DATETIME format:

$date = new DateTime('12MAR2009', new DateTimeZone('America/New_York'));
$mysql_date = $date->format('Y-m-d H:i:s');

You can use strtotime(), but timezone handling with it is kind of a pain.

Mark Trapp
+1 for mentioning time zones. Dates / datetimes should always be saved with time zone info. Otherwiese, both users moving around, and moving around of the servers are potential sources of errors.
chryss
Currently my application revolves around basic UTC time - your point is valid should I require keeping a log of timings specific to each user based upon where they are. I'll keep that in mind in another project - thanks again.
Ali