PHP date function is returning the day in place of the month

Asked

Viewed 148 times

3

I need to format the date received from a $_POST as follows:

date('Y-m-d', strtotime($_POST['data'])); ///O POST está enviando 10/05/2019 << Dia/Mês/Ano.

But the return of that function was meant to be 2019-05-10, is not returning this.

This function is returning 2019-10-05, that is, the value of day is in place of the value of month (Year-Day-Month).

How can I fix this?

1 answer

6


According to the documentation, when the string is in the formed "xx/yy/zzzz", it is interpreted as "month/day/year".

One option to resolve this is to use DateTime::createFromFormat to do the Parsing (indicating the format the string is in), and then format to convert the date to the desired format:

$d = DateTime::createFromFormat('d/m/Y', '10/05/2019');
echo $d->format('Y-m-d'); // 2019-05-10

Or, if you prefer procedural style:

$d = date_create_from_format('d/m/Y', '10/05/2019');
echo date_format($d, 'Y-m-d'); // 2019-05-10

The same documentation still shows other formats that are interpreted as "day month year", such as when hyphen or dot is used as separator. So just make a replace, replacing the bar with one of these tabs:

$data = '10/05/2019';
// trocar barra por hífen
echo date('Y-m-d', strtotime(preg_replace('{/}', '-', $data)));
// trocar barra por ponto
echo date('Y-m-d', strtotime(preg_replace('{/}', '.', $data)));

Both print 2019-05-10.


The function preg_replace requires a regex in the first parameter (so the bar is written as {/}). But in this case, as the replacement is simpler, you can simply use str_replace:

$data = '10/05/2019';
// trocar barra por hífen
echo date('Y-m-d', strtotime(str_replace('/', '-', $data)));
// trocar barra por ponto
echo date('Y-m-d', strtotime(str_replace('/', '.', $data)));

Browser other questions tagged

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