I have a date time coming in from a select form with the format of 12:00 PM Sat Mar 15 purely for aesthetic reasons. The PHP strtotime function converts this to (and more than likely rightfully so): 1394866800.

However, when I prepare the time for my database $db_time = date('Y-m-d H:i:s', $time_req); I get 2014-03-15 00:00:00. Is there a way to keep my visually appealing time display yet enter the correct format in my MySQL database?

有帮助吗?

解决方案

The problem is that your input is in a non-standard format, because the time comes first, then the day of the week, then the month and day of the month. You need to tell PHP how to interpret this.

You can use date_create_from_format, like so:

$formatted_date = '12:00 PM Sat Mar 15';
// to use your POST data, use $formatted_date = $_POST['time_req'];
echo date_create_from_format('H:i A D M j', $formatted_date)->format('Y-m-d H:i:s');

Output:

2014-03-15 12:00:00

Note: the above is the one-liner, procedural version of the method DateTime::createFromFormat, as pointed out by @MarkBaker in the comments. You could also do:

$formatted_date = '12:00 PM Sat Mar 15';
// to use your POST data, use $formatted_date = $_POST['time_req'];

// create an object
$mydate = DateTime::createFromFormat('H:i A D M j', $formatted_date);
// invoke the format method
echo $mydate->format('Y-m-d H:i:s');

其他提示

Use DateTime::createFromFormat()

$st = "12:00 PM Sat Mar 15";

$datetime = DateTime::createFromFormat("H:i A D M j", $st);
$mysql_formatted = $datetime->format("Y-m-d H:i:s");
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top