Datediff gives me a Boolean value when comparing two dates

0

I have a login.php in which a user is valid, and if it is the correct one, I open the session. The code is as follows:

    if (password_verify($pass,$resultado)) {
                        session_start();
                        $_SESSION['nick'] = $nickjugador;
                        $_SESSION['instante'] = time();
                        echo "Enhorabuena ".$_SESSION['nick'].", te has logueado, puedes acceder a <a href='cpanel.php'>Panel de control</a>";
                    }
                    else {
                        die(

"El nombre o la contraseña no coinciden");
                }

In cpanel php I want to calculate the difference between the time in which the session was started and if the difference is of 3 and a half hours, or of 4 hours, that the session is closed. However when I do a vardump of datediff()$diferencia = date_diff($_SESSION['instante'], $fechanueva); it returns a Boolean value.

    
asked by ras212 09.07.2017 в 10:03
source

2 answers

2

If you assign the "instant" with time() you are assigning an integer, not a date. You can try something like this:

$fechanueva1 = date("2017-07-08 08:20:30");
$fechanueva2 = date("Y-m-d H:i:s");

if( is_string( $fechanueva1)) $fechanueva1 = date_create( $fechanueva1);
if( is_string( $fechanueva2)) $fechanueva2 = date_create( $fechanueva2);

$diferencia = date_diff($fechanueva1, $fechanueva2);
var_dump($diferencia);

The result will be an object of the class DateInterval :

object(DateInterval)[3]
  public 'y' => int 0
  public 'm' => int 0
  public 'd' => int 1
  public 'h' => int 0
  public 'i' => int 0
  public 's' => int 33
  public 'weekday' => int 0
  public 'weekday_behavior' => int 0
  public 'first_last_day_of' => int 0
  public 'invert' => int 0
  public 'days' => int 1
  public 'special_type' => int 0
  public 'special_amount' => int 0
  public 'have_weekday_relative' => int 0
  public 'have_special_relative' => int 0
    
answered by 09.07.2017 / 10:21
source
1

Did you edit your code? I think I've seen before that in the session you put the result of date (), which returns a string, you can try the following:

if ( isset( $_SESSION[ 'instante' ])) {

    $instante = date_create( $_SESSION[ 'instante' ]); //si guardo resultado de date()
    $fechanueva = date_create( date( "Y-m-d H:i:s" ));

    $diferencia = date_diff( 
        $instante, 
        $fechanueva 
    );


    echo "<pre>"; var_dump( $diferencia ); //Debug ressults

} else {

    //Tratar error
}
    
answered by 09.07.2017 в 11:35