I'm trying to invert a date variable that displays the results like this:
2016/05/20
But I want a function in php that looks like this:
20/05/2016
How to do this?
I'm trying to invert a date variable that displays the results like this:
2016/05/20
But I want a function in php that looks like this:
20/05/2016
How to do this?
You can do this with data()
and stringtotime()
like this:
echo date("d/m/Y", strtotime("2016/05/20"));
Another option is to treat as a normal string, split with explode()
, reverse order with array_reverse()
, and merge into a string again with implode()
. In this case it would look something like this:
echo implode("/", array_reverse(explode("/", "2016/05/20")));
Example: link
I already answered something similar a few days ago, if you wanted to see the answer is explode " and then merge them again with the "implode ", I used the array_reverse "to do the inversion, but as it is a date you could do this manually.
Example used inversion by PHP
<?php
// Sua data
$data = "2016/05/20";
// Quebra a data nos "/" e transforma cada pedaço numa matriz
$divisor = explode("/", $data);
// Inverte os pedaços da data (via PHP)
$reverso = array_reverse($divisor);
// Junta novamente a matriz em texto
$final = implode("/", $reverso);
// Imprime os resultados na tela
echo $final;
?>
Example reversing "manually"
<?php
// Sua data
$data = "2016/05/20";
// Quebra a data nos "/" e transforma cada pedaço numa variavel
list($ano, $mes, $dia) = explode("/", $data);
// Monta a data de volta no formato certo
$data_nova = ($dia . "/" . $mes . "/" . $ano);
// Imprime os resultados na tela
echo $data_nova;
?>
If you are procedurally programming an option, use the date_format
function:
$date = date_create("2016/05/08");
echo date_format($date,"d/m/Y");
If you are using the Object Orientation approach you can use format
:
$data_string = '2016/05/08';
$data = new DateTime($data_string);
echo $data->format('d/m/Y');
But it's a question with n possible solutions.
References: