Failure to compare dates before saving to the bank

Asked

Viewed 71 times

4

I’m trying to do a date validation, if the date DataInicial is smaller than the DataAtual, that is, can not be retroactive the script should return me an error message with json_encode not allowing the flow to continue, which is not happening. What I did was this, look:

 if ($_POST["Operacao"] == 'Inserir') { 

    $IdColaborador = $_POST['IdColaborador'];
    $IdUnidade = $_POST['IdUnidade'];
    $IdDepartamento = $_POST['IdDepartamento']; 

    // DATA ATUAL
    $DataAtual = date('Y-m-d');

    // FORMATANDO A DATA PARA GRAVAÇÃO NO BD    
    $DataInicial = date('Y-m-d',strtotime(str_replace('/', '-', $_POST['dDataInicial']))); // converte datas em formato 'br' para sql.
    $DataFinal = date('Y-m-d',strtotime(str_replace('/', '-', $_POST['dDataFinal']))); // converte datas em formato 'br' para sql.  

    // VERIFICANDO SE DATA É RETROATIVA
    if ( strtotime($DataInicial) < strtotime($DataAtual) ) {
        $aretorno["msg"] = "A data não pode ser retroativa";
        $aretorno["status"] = "ERRO";   
    }

    $dHoraInicial = $_POST['dHoraInicial'];
    $dHoraFinal = $_POST['dHoraFinal'];
    $sAssunto = $_POST['sAssunto'];
    $sLocal = $_POST['sLocal']; 
    $sDescricao = $_POST['sDescricao'];

    mysql_select_db($database_pcon, $pcon);
    $sql = "INSERT INTO agendaMural (IdColaborador, IdUnidade, IdDepto, DataInicial, HoraInicial, DataFinal, HoraFinal, Assunto, Local, Descricao ) VALUES ('$IdColaborador', '$IdUnidade', '$IdDepartamento', '$DataInicial', '$dHoraInicial', '$DataFinal', '$dHoraFinal', '$sAssunto', '$sLocal', '$sDescricao')";
    $query = @mysql_query($sql,$pcon);

    if ($query) {
        $aretorno["msg"] = "Registro inserido com sucesso";
    } else {
        $aretorno["msg"] = "Erro: " . $sql . "<br>" . mysql_error($pcon);
        $aretorno["status"] = "ERRO";
    }
}

// FECHA CONEXÃO COM BD
mysql_close($pcon);

// RETORNAR STATUS - MENSAGEM DA EXECUÇÃO
header('Content-Type: application/json');
echo json_encode($aretorno);
  • This is all wrong: if ( strtotime($DataInicial) " . mysql_error($pcon); shouldn’t be a { ?

  • Hello @rray, in my view, before publishing the code appears right, but after published gets this error, I will edit.

  • I believe that strtotime($DataInicial), is unnecessary since the assignment of the variable is already a type date.

2 answers

5


You can check if the date is retroactive with the class Datetime, through property invert, on returning 1 means that the result of the calculation is negative if it is 0 is positive, use diff() to calculate the difference between the dates.

<?php

$hoje = new DateTime();
$dataInicial = DateTime::createFromFormat('d/m/Y', '10/11/2015');

$resultado = $hoje->diff($dataInicial);

if($resultado->invert){
    echo 'data retroativa';
}else{
    echo 'data no periodo';
}
  • Interesting that ->invert. The variable $resultado returns a boolean?

  • @Diegofelipe $resultado is a dateInterval

  • Hi @rray, how can I use the variable that comes from my form on that line? $stardate = Datetime::createFromFormat(’d/m/Y', '10/11/2015')?

  • 1

    @adventistapr, this can exchange that fixed date for a variable. If you need to convert it to record in the bank do: $dataInicial->format('Y-m-d');

  • Hello @rray, thank you so much for the excellent tip and help, the code was perfect.

  • 1

    @adventistapr simple code is the idea :)

Show 1 more comment

1

<?php

$hoje = new DateTime();
$dataInicial = DateTime::createFromFormat('d/m/Y', '10/11/201<?php

$hoje = new DateTime();
$dataInicial = DateTime::createFromFormat('d/m/Y', '10/11/2015');

$resultado = $hoje->diff($dataInicial);

if($resultado->invert){
    echo 'data retroativa';
}else{
    echo 'data no periodo';
}5');

$resultado = $hoje->diff($dataInicial);

if($resultado->invert){
    echo 'data retroativa';
}else{
    echo 'data no periodo';
}

And if in this example of invert I want to put an Else if for if the date is equal I put a evo like "On time" ?

Browser other questions tagged

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