hacket
hacket

Reputation: 1161

Convert unconventional string to mysql datetime?

I am completely new to php and am wondering how I could go about converting this string :

Tue Jan 17 09:17:15 CST 2012

into a format that would fit into a MySQL datetime format (24 hour) of

01-17-2009 09:17:15

I have found the MySQL function FROM_UNIXTIME() that is said to convert from a PHP Timestamp to MySQL DateTime. My problem is getting that original string to the correct PHP Timestamp format.

Upvotes: 1

Views: 2002

Answers (3)

artragis
artragis

Reputation: 3713

You can use \DateTime::createFromFormat if you have php >= 5.3. I prefer this solution over the strtotime one as to manipulate date you use something that means "date" instead of an integer.

$date = \DateTime::createFromFormat('D M d h:i:s T Y',$dt);

Upvotes: 0

JvdBerg
JvdBerg

Reputation: 21856

A quick try:

$dt = 'Tue Jan 17 09:17:15 CST 2012';
$ts = strtotime( $dt );

echo date('Y-m-d G:i:s', $ts);

outputs: 2012-01-17 16:17:15

The time difference comes from the timezone. My server is on UTC+1 and CST is UTC-6

Upvotes: 2

iouri
iouri

Reputation: 2929

You can also use mysql function, I am not sure about timezone though.

select DATE_FORMAT(STR_TO_DATE('Tue Jan 17 09:17:15 CST 2012','%a %b %e %h:%i:%s CST %Y'),'%m-%d-%Y %h:%i:%s');

Upvotes: 0

Related Questions