If条件为2个时间戳与日期的差异在php

kuuvgm7e  于 2023-05-05  发布在  PHP
关注(0)|答案(2)|浏览(103)

我有一个表,将存储过期的时间戳。我想存储它们之间的时间间隔1天前一个给定的时间戳,直到3天后。
我试过这个:

$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";
}

但这不会返回正确的结果。
任何建议将不胜感激。

xdnvmnnf

xdnvmnnf1#

您的代码所写的具体问题:
strtotime()接受一个日期字符串,但你给它一个时间戳。你需要给它输入$nowTime,例如:

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

此外,如果你使用DateTime函数,你就不必在字符串之间来回转换,而只需要依赖函数就能神奇地知道你的日期格式是什么:

$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')
);

输出:

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对象比strtotime()等旧的实用程序函数允许更多的控制,特别是当你需要对时区做任何事情的时候。
参考:https://www.php.net/manual/en/book.datetime.php

r1zk6ea1

r1zk6ea12#

这很有效:

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";
}

我添加默认时区并从现在时间中删除秒,并将=添加到< or >现在工作,结果对每个时间戳都为true

相关问题