Reputation: 5568
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.
Upvotes: 0
Views: 10110
Reputation: 10732
$three_min_from_now = mktime(0, 3, 0, 0, 0, 0);
if (time() >= $filemodtime + $three_min_from_now) {
What you're doing here is checking if time() is larger than the unix timestamp for the file modification, plus the unix timestamp for three minutes from now. It's very, very unlikely to be true - you're much better off just adding 180 to $filemodtime:
if (time() >= $filemodtime + (60 * 3)) {
Upvotes: 5
Reputation: 24671
My suggestion would be to redo your if statement like this:
if((time() - $filemodtime) >= 180)
It removes the need to calculate expressly when '3 minutes from now' occurs
Upvotes: 3
Reputation: 11264
if (file_exists($filename)) {
$filemodtime = filemtime($filename);
}
if (time() - $filemodtime > (3*60)) {
// it been more than 3 minutes
} else {
// do other stuff
}
simply compare two integer timestamp values...
Upvotes: 1