skip to Main Content

I have a tabe that store expires timestamps
I want do something between 1 day before timestamps until 3 days after that

I try this:

$timeStamp = 1682936936; //2023-5-1 13:58 for example
$nowTime = strtotime(date("Y-m-d H:i:s"));

$oneDayBefore = strtotime("-1 day",$timeStamp);
$threeDaysAfter = strtotime("+3 days",$timeStamp);

if($nowTime > $oneDayBefore && $nowTime < $threeDaysAfter){
    echo "yes";
}
else{
    echo "no";
}

but return not correct results

2

Answers


  1. Chosen as BEST ANSWER

    this worked good:

    date_default_timezone_set('Asia/tehran');
    $timeStamp = 1682936936; //2023-5-1 13:58 for example
    $nowTime = strtotime(date("Y-m-d H:i")); // edit: delete secend
    
    $oneDayBefore = strtotime("-1 day",$timeStamp);
    $threeDaysAfter = strtotime("+3 days",$timeStamp);
    
    if($nowTime >= $oneDayBefore && $nowTime <= $threeDaysAfter){
        echo "yes";
    }
    else{
        echo "no";
    }
    

    i add default timezone and remove second from now time and add = to < or > now work and results is true for every timestamp


  2. Specific problem with your code as-written:

    strtotime() takes a date string, but you’re giving it a timestamp. You need to feed it $nowTime instead, eg:

    $oneDayBefore = strtotime("-1 day",$nowTime);
    $threeDaysAfter = strtotime("+3 days",$nowTime);
    

    Also, if you use the DateTime functions instead you don’t have to convert back and forth between strings and rely on functions just magically knowing what your date format is:

    $timeStamp = 1682936936;
    
    $now   = (new DateTime())->setTimestamp($timeStamp);
    $begin = (clone $now)->sub(new DateInterval('P1D'));
    $end   = (clone $now)->add(new DateInterval('P3D'));
    
    if( $now > $begin && $now < $end){
        echo "yes";
    }
    else{
        echo "no";
    }
    echo PHP_EOL;
    
    var_dump(
        $now->format('U'),
        $now->format('c'),
        $begin->format('U'),
        $begin->format('c'),
        $end->format('U'),
        $end->format('c')
    );
    

    Output:

    yes
    string(10) "1682936936"
    string(25) "2023-05-01T12:28:56+02:00"
    string(10) "1682850536"
    string(25) "2023-04-30T12:28:56+02:00"
    string(10) "1683196136"
    string(25) "2023-05-04T12:28:56+02:00"
    

    DateTime object allow far more control than the old utility functions like strtotime(), especially if you need to do anything with timezones.

    Ref: https://www.php.net/manual/en/book.datetime.php

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search