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

1
  • 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 Commented Nov 10, 2015 at 15:41

2 Answers 2

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]);
Sign up to request clarification or add additional context in comments.

2 Comments

you missed something. His format should actually be 'd/m/y H:i:s' since he has the two digit years.
Thanks it worked \DateTime::createFromFormat('d/m/y H:i:s', $process_date[0]);
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".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.