문제

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