【问题标题】:Php check if 24hours has passed in a specific timezonephp 检查特定时区是否已过 24 小时
【发布时间】:2021-04-03 09:07:54
【问题描述】:

我想检查从生成令牌开始是否已经过了 24 小时。当我创建一个令牌时,我保存当前时间戳并在使用令牌之前检查时间戳是否有效,我尝试了下面的代码但没有成功,即使时间戳超过 2 天,它也会一直显示令牌有效。

<?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 24hours\n";
}else{
    if(($timestamp - $currentTimestamp) > $time2Hours){
        echo "Token is less than 24hours but still more than 2hours required duration\n";
    }else{
        echo "Token is active\n";

    }
}
echo date('m/d/Y H:i:s', $timestamp);
?>

我也试过了

<?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 24hours\n";
}else{
    if($currentTimestamp < $timestamp->modify('-2 hour')){
        echo "Token is less than 24hours but still more than 2hours required duration\n";
    }else{
        echo "Token is active\n";

    }
}
echo date('m/d/Y H:i:s', $timestamp->getTimestamp());
?>

【问题讨论】:

  • 你能粘贴dump $timestamp-&gt;modify('-24 hour')的输出吗

标签: php datetime timestamp timezone


【解决方案1】:
if(($currentTimestamp - $timestamp) > $time24Hours){
    echo "Token is more than 24hours\n";
}else{
    if(($currentTimestamp - timestamp) > $time2Hours){
    ...

你的 if 中只有一个小的逻辑错误 - 交换 $currenTimestamp 和 $timestamp

$currentTimestamp (通常)总是比你保存的$timestamp 大,所以如果你从 currentTimestamp 中减去时间戳,结果将是

“自保存时间戳以来经过的秒数”

如果此持续时间大于 24 小时 ==> 令牌过期

就像信息一样:如果您只处理时间戳,则时区并不真正相关。时间戳始终独立于时区。如果您想检查 24 小时的差异,只需使用时间戳即可。如果您想检查“1 天”,它会有所不同,因为一天的长度可能会受到例如冬季/夏季时间变化

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多