Convert MySQL data (YYYY / mm / dd h: m: s) to dd / mm / yyyy

4

Look at my database:

I'musingthefollowingcode:

<?php$data=$noticia->data_cadastro;setlocale(LC_ALL,"pt_BR", "pt_BR.iso-8859-1", "pt_BR.utf-8", "portuguese");
date_default_timezone_set("America/Sao_Paulo");
echo strftime("%A, %d de %B de %Y", strtotime($data));
?>

Variable contents: $data : var_dump: "string '09/02/2015 15:55:30' (length=19)"

Returns in the format: "Wednesday, September 02, 2015".

I would like it to return "Monday, February 9, 2015"; and then customize for "09 February 2015", what do I do?

It differs from the post: " Format date in PHP " because where is echo strftime( '%A, %d de %B de %Y', strtotime('today')); in my case has a variable $date , simple, but it's making a difference in my case.

    
asked by anonymous 23.02.2015 / 14:56

4 answers

4

This should work:

setlocale(LC_ALL, "pt_BR", "pt_BR.iso-8859-1", "pt_BR.utf-8", "portuguese");
date_default_timezone_set('America/Sao_Paulo');

$olddata = '09/02/2015 15:55:30';
$data = str_replace('/', '-', $olddata);

// Formato para por no Layout (pedido antes da edição da pergunta)
echo strftime("%m %B de %Y", strtotime($data)); // 02 fevereiro de 2015

// Como pedido após a edição da pergunta, personalizar a data para 09 de fevereiro de 2015
echo strftime("%d de %B de %Y", strtotime($data)) // 09 de fevereiro de 2015 

DEMO

    
23.02.2015 / 15:14
4

You can do this directly in the mysql query

Using DATE_FORMAT()

Example

SELECT *, DATE_FORMAT(data_cadastro,'%d/%m/%Y') AS data_formatada FROM sua_tabela 
    
23.02.2015 / 15:21
4

If you want to return only 09 Fevereiro 2015 , then do so:

setlocale(LC_ALL, "pt_BR", "pt_BR.iso-8859-1", "pt_BR.utf-8", "portuguese");

echo strftime("%d %B %Y", strtotime($data));

In your example, there seems to be an interpretation error between mm and dd , and vice versa.

In this case, this solution would work, but I still recommend that you identify if there is any date formatting error caused by regionalization.

$data = DateTime::createFromFormat('m/d/yy', $noticia->data_cadastro)->getTimestamp();

echo strftime("%d %B %Y", $data);

See that we created the date from the format m/d/yy , not d/m/yy , because of the formatting of your date.

Update

However, if you want to do exactly as it is in the question title, that is "Convert MySQL data (YYYY / mm / dd h: m: s) to dd / mm / yyyy" , then you can do so.

echo DateTime::createFromFormat('yy/m/d H:i:s', $data)->format('d/m/Y');
    
23.02.2015 / 15:05
2

I do not know if it works in MYSQL , but not PostgreSQL would be equivalent to

to_char(data_cadastro, 'DD/MM/YYYY')
    
23.02.2015 / 20:03