Convert date to dd/mm/yyyy format

Asked

Viewed 38,375 times

9

I’m getting two PHP post of two dates in format dd/mm/yyyy, however to display the data need to convert dd/mm/yyyy for yyyy-mm-dd.

Code:

if (isset($_POST)) // Se existir o array post, pq ele não retorna undefined index.
{

  $data1 = $_POST["data1"];
  $data2 = $_POST["data2"];

  $busca = mysql_connect("$local", "$usuario", "$senha") or die("ERRO AO CONECTAR AO MYSQL, VERIFIQUE COM O ADMINISTRADOR".mysql_error());
  mysql_select_db("$banco") or die("BASE DE DADOS INVÁLIDO");
  mysql_select_db("$banco") or die("BASE DE DADOS INVÁLIDO");

  $pesquisa = mysql_query("SELECT sum(ProdValor) FROM vendas WHERE data BETWEEN '$data1' AND '$data2' AND StatusTransacao = 'Aprovado' ");

  while ($sum = mysql_fetch_array($pesquisa)) {
    $soma2 = $sum['sum(ProdValor)'];
  }

  echo '<b>Aprovado</b> '.$soma2.
  '<br>';

}
   

5 answers

11

If it’s for php, You can use the functions date and strtotime to return the date in the desired format.

<?php

    $data = str_replace("/", "-", $_POST["data1"]);
    echo date('Y-m-d', strtotime($data));

10


MYSQL - Can be done directly using the function DATE_FORMAT() thus:

DATE_FORMAT(suadatadd/mm/yyyy,'%d/%m/%Y') as 'DATA'

PHP - Can be made a Function:

public static function dateEmMysql($dateSql){
    $ano= substr($dateSql, 6);
    $mes= substr($dateSql, 3,-5);
    $dia= substr($dateSql, 0,-8);
    return $ano."-".$mes."-".$dia;
}

http://www.w3schools.com/sql/func_date_format.asp

  • Thank you @Maison Sakamoto

9

15/12/2018 -> 2018-12-15

$data = implode('-', array_reverse(explode('/', "15/12/2018")));

2018-12-15 -> 15/12/2018

$data = implode('/', array_reverse(explode('-', "2018-12-15")));

1

echo date('Y-m-d H:i', strtotime($data)); for hours and minutes together

1

STRTOTIME does not accept the dd/mm/yyyy format.

To convert dd/mm/yyyy to yyyy-mm-dd you can use the function createFromFormat and format as in the example below

DateTime::createFromFormat('d/m/Y', "20/01/2021")->format("Y-m-d");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.