I want to check if 24hour has passed from the time a token is generated. When I create a token I save the current timestamp and check if the timestamp is valid before making use of the token, I have tried below code but none worked, it keeps showing that token is valid even when the timestamp is more than 2 days.
<?php
$time24Hours = 86400;
$time2Hours = 7200;
$timestamp = 1608234028;
$timezone = "Asia/Kolkata";
$currentTimestamp = (new DateTime("now", new DateTimeZone($timezone)))->getTimestamp();
if(($timestamp - $currentTimestamp) > $time24Hours){
echo "Token is more than 24hoursn";
}else{
if(($timestamp - $currentTimestamp) > $time2Hours){
echo "Token is less than 24hours but still more than 2hours required durationn";
}else{
echo "Token is activen";
}
}
echo date('m/d/Y H:i:s', $timestamp);
?>
And I tried this also
<?php
$timezone = "Asia/Kolkata";
$timestamp = new DateTime();
$timestamp->setTimestamp(1608234028);
$timestamp->setTimezone(new DateTimeZone($timezone));
$currentTimestamp = new DateTime("now", new DateTimeZone($timezone));
if($currentTimestamp < $timestamp->modify('-24 hour')){
echo "Token is more than 24hoursn";
}else{
if($currentTimestamp < $timestamp->modify('-2 hour')){
echo "Token is less than 24hours but still more than 2hours required durationn";
}else{
echo "Token is activen";
}
}
echo date('m/d/Y H:i:s', $timestamp->getTimestamp());
?>
Advertisement
Answer
if(($currentTimestamp - $timestamp) > $time24Hours){
echo "Token is more than 24hoursn";
}else{
if(($currentTimestamp - timestamp) > $time2Hours){
You have just a small logical error in your if – swap $currenTimestamp and $timestamp
$currentTimestamp
is (normally) always bigger than your saved $timestamp
, so if you substract the timestamp from the currentTimestamp, the result will be
“elapsed seconds since saved timestamp”
If this duration is bigger than 24 hours ==> expired token
Just as info: If you are only dealing with timestamps, the timezone isn’t really relevant. A timestamp is always independant from a timezone. If you want to check for 24 hours difference, just stick to timestamps. If you want to check for “1 day” it`s different, because the length of a day can be affected by e.g. a Winter/Summer-Time change