php将字符串转换为日期时间“2012年12月21日 - 03:45 PM”

i am using bootstrap date time picker to pick date and time . its giving me output "21 December 2012 - 03:45 PM" now i want to store it on MySQL database my problem is how can i store this string to MySQL data column (data type = date time).

here i using this code but its not working

$s = '21 December 2012 - 03:45 PM';

$date = strtotime($s);
echo date('d/M/Y:H:i:s', $date);

i want to store this string to mysql datbase in date time format. extract same string on sql query run

thank you

If your input string format from that datepicker has like that:

21 December 2012 - 03:45 PM

You need to convert the format first that is applicable for your DATETIME field which is:

YYYY-MM-DD HH:MM:SS

The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD HH:MM:SS' format.

Ref: http://dev.mysql.com/doc/refman/5.1/en/datetime.html

From PHP, you could use the DateTime class. Provide the format that you have in your datepicker:

$s = '21 December 2012 - 03:45 PM'; // input from date picker
$date = DateTime::createFromFormat('d F Y - G:i a', $s);
$insert_date = $date->format('Y-m-d H:i:s');
echo $insert_date;
// rest of your mysql insertion codes

Try this one for write to mysql:

$mysqldate = date( 'Y-m-d H:i:s', $date )

MySQL expects DateTime fields to be past to it for storage in this format

YYYY-MM-DD HH:MM:SS

So change this statement to

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

And of course you have to wrap that string in quote in the SQL statement like this

$s = '21 December 2012 - 03:45 PM';

$a_date = date('Y-m-d H:i:s', strtotime($s));

$sql = "INSERT INTO table (the_date) VALUES ('$a_date')";

You'd better use epoch values instead of human readable date strings. Do all your stuff using UTC epoch values and convert into human readable strings only when you have to show the date to the user (add locale, etc..etc..).

when you do strtotime($s);
so in your view you can <?php echo date('Y-m-d H:i:s',$row['date']) ?>