0

I need to compare two Unix timestamps and I'm having trouble with the math. I know a Unix timestamp is the number of seconds since January 1, 1970. But I'm doing something wrong with the math. I'm trying to detect whether it has been 3 minutes from when the file was last modified. Here is my code:

if (file_exists($filename)) {
    $filemodtime = filemtime($filename);
}

$three_min_from_now = mktime(0, 3, 0, 0, 0, 0);

if (time() >= $filemodtime + $three_min_from_now) {
     // do stuff
} else {
     // do other stuff
}

But the else clause keeps being satisfied, not the if, even when the if should be true. I think the issue is my math. Can someone help? Thanks.

4

3 回答 3

4
$three_min_from_now = mktime(0, 3, 0, 0, 0, 0);

if (time() >= $filemodtime + $three_min_from_now) {

您在这里所做的是检查 time() 是否大于文件修改的 unix 时间戳,再加上三分钟后的 unix 时间戳。这不太可能是真的——你最好把 180 加到 $filemodtime 上:

if (time() >= $filemodtime + (60 * 3)) {
于 2012-06-22T20:30:19.630 回答
3

我的建议是像这样重做你的 if 语句:

if((time() - $filemodtime) >= 180)

它消除了在“从现在起 3 分钟”发生时明确计算的需要

于 2012-06-22T20:27:39.813 回答
1
if (file_exists($filename)) {
    $filemodtime = filemtime($filename);
}

if (time() - $filemodtime > (3*60)) {
     // it been more than 3 minutes
} else {
     // do other stuff
}

只需比较两个整数时间戳值...

于 2012-06-22T20:27:22.873 回答