Problems with date transform function

2

$data           			= $_POST["data"];	

// Recebe a variável com a data, e cria um objeto DateTime a partir do formato especificado.
$objetoData = DateTime::createFromFormat('d/m/Y', $data);

// Reformata a data do jeito desejado
$data = $objetoData->format('Y-d-m');

To this function where the same makes the exchange date to the format I desire. Example the date enters as 12/13/2018 and when it goes through the exit function 2018-12-13.

The problem is that the function is only working for old dates using the above example only works from day 12 back to day 13 and the current one shows another date that would be 2019-12-01.

    
asked by anonymous 14.12.2018 / 03:18

1 answer

6

Let's look at your code:

$data = "12/13/2018";
$objetoData = DateTime::createFromFormat('d/m/Y', $data);

In the variable $data you have 3 pieces of string 12 , 13 and 2018 separated by slash. In the DateTime object you set format to d , m and Y separated by slash. This means that:

d = 12
m = 13 (mês que não existe)
Y = 2018

So, by default, the object was created for the beginning of 2019, because the year it was informed was 2018. That's why it works up to 12.

Solution:

You can change the format to m/d/Y or you can change the date to "13/12/2018" . You need to see what is best for your algorithm.

It would look like this:

$objetoData = DateTime::createFromFormat('m/d/Y', $data);
    
14.12.2018 / 03:40