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)));
Thanks Thanks Thanks!
– Bruno Oliveira