Convert date format to php

3
I'm working with Wordpress php and I get from the database a date in the following format: "October 22, 2018", plus I need to convert it to "2018-10-22", How do I get this?

I tried:

date('Y-m-d', strtotime(get_post_meta( $id_pedido, "Data de entrega", true )));

More did not work, the value returned is "1970-01-01" and not the date entered. Thanks!

    
asked by anonymous 23.10.2018 / 19:35

4 answers

2

You can use the substr() function of PHP. Ex:

$data = "22 Outubro, 2018";

$ano = substr($data,-4); //4 dos últimos 4 caracteres e o "-" para começar a contar do final.

$dia = substr($data,0,2; //0 do ponto inicial e 2 para dois caracteres a partir de 0.

$mes_array = explode(" ", $data);//Separa nos espaços a string "data" e transforma em um array.
$mes = $mes_array[1];//Seleciona o a segunda posição do array.
    
23.10.2018 / 19:49
1

You can mount something simpler than suggested in the link. The first step is to define two search and substitution arrays (from Portuguese to English) because the names of the months or days of the week can not be converted to a valid date if specified in Portuguese. Note that the first element of $en is a v igula that will be replaced by nothing.

Once the string has been cleaned (done with str_ireplace() ) the string suffices to call the method createFromFormat() of DateTIme set the input format that in this case is the day ( d ) following the month in full ( F ) and lastly the year with four digits ( Y ).

format() defines the formatting you want Y-m-d .

$pt = [',', 'janeiro', 'fevereiro', 'março', 'abril', 'maio', 'junho', 'julho', 'agosto', 'setembro', 'outubro', 'novembro', 'dezembro']; 
$en = ['', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

$data = DateTime::createFromFormat('d F Y', str_ireplace($pt, $en,'22 maio, 2018'));
echo $data->format('Y-m-d');

Example - ideone

    
23.10.2018 / 19:50
0

Personal thank you all I was able to solve as follows:

$data_de_entrega = get_post_meta( $id_pedido, "Data de entrega", true );
$pt = [',', 'Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro']; 
$en = ['','January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
$data_new = str_replace($pt, $en, $data_de_entrega);

echo date('Y-m-d', strtotime($data_new));
    
24.10.2018 / 13:40
-1

Try to do this:

$tempo = strtotime("22 October 2018");
echo date("Y-m-d", $tempo);

Remembering that the function expects to be informed of a string containing a US English date format, in this case, "October 22, 2018".

Note : This also applies to all other months, ie you should add the month written in English.

For more information: link

    
23.10.2018 / 19:47