Format date and time with PHP

3

I have this page that displays the emails received from the logged in user, along with their dates. I am trying to format date display by PHP but it is not working as I expected. I need the PT-BR date to appear in the first line, and in the second line the hour and the minute, but it is appearing according to the image. Can you help me ? Here is my code:

<? foreach ($resultado as &$rowmensagens) {
$datamensagem = $rowmensagens['dataenvio'];
$datamensagem = date("d/m/Y H:i:s", strtotime($datamensagem));
$horamensagem = date("H:i:s", strtotime($datamensagem));

$arr_msg = explode("/", $datamensagem);
$diamsg = $arr_msg[0];
$mesmsg = $arr_msg[1];
$anomsg = $arr_msg[2];

$arr_hora = explode(":", $horamensagem);
$hora_msg = $arr_hora[0];
$minuto_msg = $arr_hora[1]; ?>

<strong><?=$diamsg?>/<?=$mesmsg?>/<?=$anomsg?></strong>
<strong><?=$hora_msg?>:<?=$minuto_msg?></strong>

NOTE: This formatting already worked on another occasion and I just copied the structure to that page. Thank you!

    
asked by anonymous 28.07.2017 / 20:51

2 answers

6

I would suggest using this method it will be much simpler you can do it as follows

(new DateTime($datamensagem))->format('d/m/Y H:i:s');
    
28.07.2017 / 21:00
7

Well, you're complicating your code to tell the truth ... the date() function already formats the date you need, including you're already formatting it there, you just need to adjust the format yourself:

$envio = strtotime($rowmensagens['dataenvio']);
$datamensagem = date("d/m/Y", $envio);
$horamensagem = date("H:i", $envio);

and then just print. Note that you do not need to separate the string or anything, just use.

On the error that only appears at 9:00 pm, it occurs because the strtotime($datamensagem) function returns false , which is the value when the function fails. So it would probably be enough to modify the code to convert the string from the database, in the format the function understands, and save the value only once, passing this value to the date function whenever you need it.

Learn more in the function documentation and function strtotime .

    
28.07.2017 / 20:58