Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/250.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在php中比较DateTime对象不起作用_Php_Api_Datetime_Time_Web Development Server - Fatal编程技术网

在php中比较DateTime对象不起作用

在php中比较DateTime对象不起作用,php,api,datetime,time,web-development-server,Php,Api,Datetime,Time,Web Development Server,我正在制作一个API,其中我需要检查特定用户的令牌有效性,为此我使用php的DateTime函数。我在登录时保存一个令牌和当前时间,我希望令牌有效期为10分钟,因此当用户在登录后的前10分钟内发出请求时,我希望更新令牌的时间有效性 $currentTime = new DateTime(); $curTime = $currentTime->format("Y-m-d H:i:s"); $time10MinutesAgo = new DateTime("10 minutes ago");

我正在制作一个API,其中我需要检查特定用户的令牌有效性,为此我使用php的DateTime函数。我在登录时保存一个令牌和当前时间,我希望令牌有效期为10分钟,因此当用户在登录后的前10分钟内发出请求时,我希望更新令牌的时间有效性

$currentTime = new DateTime();
$curTime = $currentTime->format("Y-m-d H:i:s");
$time10MinutesAgo = new DateTime("10 minutes ago");
$time10Minutes = $time10MinutesAgo->format("Y-m-d H:i:s");
$token_time = $query1_r['token_time']; // value is stored in the db(mysql)
if (($curTime > $token_time) && ($token_time >= $time10Minutes)){}

首先我无法通过第二个条件,但现在连我的页面都无法工作

使用历元时间值进行时间比较比较比较数字比日期容易得多

$currentTime = time();
$time10MinutesAgo = strtotime('-10 minutes');
$token_time = strtotime($query1_r['token_time']); // value is stored in the db(mysql)
if(($currentTime >$token_time) && ($token_time >= $time10MinutesAgo )){}

如果已经有DateTime对象,则不要将它们转换为字符串,只需在对象之间进行比较,如下所示:

$currentTime=new DateTime();
$time10MinutesAgo=新日期时间(“10分钟前”);
$tokenTime=newdatetime($query1_r['token_time']);

如果($time10MinutesAgo
$curTime
和($code>$token\u time
$time10Minutes
是字符串,而不是
DateTime
对象。我如何使其工作?@u\u mulder为什么比较$time10MInuteAgo和$token\u time会产生问题?它会产生什么问题?@u\u mulder($curTime>$token\u time)此条件工作正常,($token\u time>=$time10分钟)这个条件不起作用。事实上,我以前使用过日期函数,并将它们转换为时间戳,但这个过程花费了更多的时间,另外我主要关心的是为什么比较$time10MInuteAgo和$token\u time会产生问题?@PrakharSharma我不会对时间使用字符串比较,使用整数与历元比较会容易得多格式化。@PrakharSharma不客气,请接受我的回答:)