1

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

Community
  • 1
  • 1
Saad
  • 1,155
  • 3
  • 16
  • 36
  • I believe you need to replace the `/` in your process_date array with a `-` so that the dates are as such `27-10-15 17:00:00` – Dale Nov 10 '15 at 15:41

2 Answers2

4

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]);
FrancoisBaveye
  • 1,902
  • 1
  • 18
  • 25
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".

Audite Marlow
  • 1,034
  • 1
  • 7
  • 25