Problems with date transformation function

Asked

Viewed 74 times

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');

I have this function where it changes the date to the format I want. Example the date enters as 12/13/2018 and when pass the exit function 2018-12-13.

The problem is that the function is only worked for old dates using the example above only works from day 12 behind day 13 q the current it shows another date that would be 2019-12-01.

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, 13and 2018separated by slash. On the object DateTime you configure the format in d, m and Yseparated by slash. This means that:

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

Therefore, by default, the object was created for the beginning of the month 2019, because the year that was reported was 2018. Why it works up to 12.

Solution:

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

It would look like this for example:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.