I have an array called $process_date
with two elements. The elements are in this format dd/mm/yy H:i:s
$process_date = array(
"27/10/15 17:00:00",
" 27/10/15 18:00:00"
)
I need to convert it to mysql datetime format to query a field in my database. I tried
$myDateTime = \DateTime::createFromFormat('d-m-Y H:i:s', $process_date[0]);
$newDateString = $myDateTime->format('Y-m-d H:i:s');
And I get
Call to a member function format() on a non-object
I found this link "Call to a member function format() on a non-object" when converting date in PHP and tried
$myDateTime = new \DateTime($process_date[0]);
$myDateTime->format('Y-m-d H:i:s');
I get
DateTime::__construct(): Failed to parse time string (27/10/15 17:00:00) at position 0 (2): Unexpected character
Am I missing something?
Thanks in advance
The elements are in this format dd/mm/yy H:i:s
You have d/m/y
values, and try to extract with the format d-m-y
. Use this instead :
$myDateTime = \DateTime::createFromFormat('d/m/y H:i:s', $process_date[0]);
Try something like this:
$dateArray = array(
'27/10/15 17:00:00',
'27/10/15 18:00:00',
);
$formattedDateArray = array();
foreach ($dateArray as $date) {
$myDateTime = \DateTime::createFromFormat('d/m/y H:i:s', $date);
$formattedDateArray[] = $myDateTime->format('Y-m-d H:i:s');
}
Note the lowercase "y" for year, as the year format is 2 decimals only. "Y" will output the year as "0015", whereas "y" will output as "2015".