Short answer
$date1 = DateTime::createFromFormat('Y-m-d', "2019-03-27");
echo $date1->format('d/m/Y');
Exit:
27/03/2019
Long answer
As stated above here, here and here:
Dates have no format
A date is just a concept, an idea: it represents a specific point in the calendar.
The date of "March 27, 2019" represents this: the specific point of the calendar that corresponds to March 27, 2019.
To express this idea in text form, I can write it in different ways:
- 27/03/2019 (a common format in many countries, including Brazil)
- 3/27/2019 (American format, reversing day and month)
- 2019-03-27 (the format ISO 8601)
- 27 March 2019 (in good Portuguese)
- March 27th, 2019 (in English)
- 2019 年 3 月 27 日 (in Japanese)
- and many others...
Note that each of the above formats is different, but all represent the same date (the same numerical values of the day, month and year).
That said, to string 2019-03-27
is not a date, but one of the many possible ways of representing a.
Already one DateTime
is an object representing the idea (the concept) of a date, and it alone does not have a format.
So what you should do is:
- convert the string
2019-03-27
for a DateTime
- convert this
DateTime
in another string, with the desired format
The first step is done with DateTime::createFromFormat
, which takes the format and its string as a parameter.
The second step is done with the method format
, that converts the DateTime
to a string, using some specific format.
In your code you’re using format
ahead of time, and ends up passing the string 27/03/2019
for the builder of DateTime
. But according to the documentation, when a string like this is passed (using bars as separators), it is interpreted in American format (month/day/year). And since "27" is not a valid month, it makes the mistake.