How to compare datatime to a date

Asked

Viewed 43 times

0

I have a problem in my login system, I want by validity system however I am not able to compare the current datatime with the received expiration datatime.

I tried to use the following code and it didn’t work:

$usuario = mysqli_real_escape_string($conexao, $_POST['usuario']);
$senha = mysqli_real_escape_string($conexao, $_POST['senha']);
$query = "select usuario from usuario where usuario = '{$usuario}' and senha = md5('{$senha}')";
$result = mysqli_query($conexao, $query);
$row = mysqli_num_rows($result);
if($row == 1) {
    $_SESSION['usuario'] = $usuario;
    $resultado = $conexao->query($consulta);
    while($row = $resultado->fetch_assoc()) {
        if($_SESSION['usuario'] == $row['usuario'])
            $id = $row['usuario_id'];
            $dateTime = new DateTime();
            $sql1 = "UPDATE usuario SET last_ip='".$_SERVER['REMOTE_ADDR']."', last_date='".$dateTime->format('Y-m-d H:i:s')."'  WHERE usuario_id='".$id."'";
            $result = mysqli_query($conexao, $sql1)

            $d2 = strtotime($row['exp']); # recebendo expiração no caso (2020-04-02 00:00:00)
            $d1 = strtotime($dateTime->format('Y-m-d H:i:s')); # recebendo nova data

            if($d1 >= $d2){ # tentando comparar...
                unset($_SESSION['usuario']);
                header('Location: index.php');
                $_SESSION['codigo2'] = 0;
                exit();
            }
    }
}

1 answer

3


If you’re using DateTime, there’s no reason to mix with strtotime. There is also no reason to transform the DateTime string (using format), just to pass this string to strtotime.

Just turn the string containing the expiration date into a DateTime, using createFromFormat, and compare it to the current date:

$hoje = new DateTime();
$data_expiracao = DateTime::createFromFormat('Y-m-d H:i:s', '2020-04-02 00:00:00');

if ($data_expiracao < $hoje) {
    // expirou
} else {
    // não expirou
}

Remembering that the comparison takes into account the time as well, and new DateTime() will create a DateTime containing the current time.

If you want the independent comparison of the time, taking into account only the day, just set both dates for the same time. Ex:

$hoje = new DateTime();
$hoje->setTime(0, 0); // setar horário para meia-noite
$data_expiracao = DateTime::createFromFormat('Y-m-d H:i:s', '2020-04-02 15:00:00');
$data_expiracao->setTime(0, 0);
  • Unresolved :(yet I was unable to compare both DATES

  • @Gustavoalves As I don’t have access to your database, all I can do is test with the data you provided (i.e., the string "2020-04-02 00:00:00"), and with that data the comparison works. If it didn’t work then there is more detail in other points of the code, because to create the dates and compare them just do what I showed there.

Browser other questions tagged

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