-1

I am receiving a date from Apple as Mar 5, 2020 at 9:18 AM. I believe this is M j, Y at G:i A but their string has an added at.

I tried to do this..

$origDate = "Mar 5, 2020 at 9:18 AM"
$date = DateTime::createFromFormat('M j, Y at G:i A', $origDate);
echo $date->format('yyyy/MM/dd HH:mm');

But I get the following error.

Uncaught Error: Call to a member function format() on boolean

How can I fix this?

letsCode
  • 2,774
  • 1
  • 13
  • 37
  • What is MMM? Also yyyy? Your string is all wrong.. – Wimanicesir Mar 05 '20 at 15:10
  • 2
    Please read the [documentation](https://www.php.net/manual/en/datetime.createfromformat.php) to see what the formats look like. All format identifiers are single characters, not multiples. – aynber Mar 05 '20 at 15:10
  • `Uncaught Error: Call to a member function format() on boolean` is because `$date` is not a `DateTime` object, it's `FALSE`, because `DateTime::createFromFormat()` failed. – Havenard Mar 05 '20 at 15:12
  • Does this answer your question? [Convert one date format into another in PHP](https://stackoverflow.com/questions/2167916/convert-one-date-format-into-another-in-php) – mw509 Mar 05 '20 at 15:17

1 Answers1

8

All Date format identifiers are single characters (Y), not multiple (YYYY). Also, actual strings (at) will need to be escaped. You would need to create the DateTime object like this:

$origDate = "Mar 5, 2020 at 9:18 AM";
$date = DateTime::createFromFormat('M d, Y \a\t g:i A', $origDate);
echo $date->format('Y/m/d H:i');

As I mentioned in my comment, you can see all of the format identifiers at https://www.php.net/manual/en/datetime.createfromformat.php

aynber
  • 22,380
  • 8
  • 50
  • 63
  • Clean and correct. However, instead of escaping your string, you could always remove them from the string before parsing it to a date. This works just as good though. – Wimanicesir Mar 05 '20 at 15:17
  • @Wimanicesir Too much trouble to go through just to remove 2 characters. Skipping them works best. – Havenard Mar 05 '20 at 15:19
  • str_replace('at','',$origdate) is not that much trouble. I just wanted to point out that preparing your string before parsing is also an option. Maybe not in this exact use case but for other situations. Once again, this works just as well. – Wimanicesir Mar 05 '20 at 15:21
  • Let me rephrase that. Using the escape sequence makes your code more lean-and-mean and easier to read, which is good coding. It also respects that `$origDate` is in a proper date format and doesn't need to have this information dug out from it, only converted. – Havenard Mar 05 '20 at 15:30
  • Thanks so much!!! I was looking at a website that had the wrong characters!! – letsCode Mar 05 '20 at 15:33