0

I have a specific timestamp stored in $user_timestamp, which could be for example 1421942631. And I have the current timestamp stored in $current_timestamp.

I want to compare the timestamp in this variable with the current timestamp and check if it has gone 3 days. If it has, then do action.

How can I do this in a basic if statement?

John Conde
  • 217,595
  • 99
  • 455
  • 496
Henrik Petterson
  • 6,862
  • 20
  • 71
  • 155

2 Answers2

1

Although I typically recommend using DateTime for date math, you could just use relative formats with strtotime() to keep it simple.

if($user_timestamp < strtotime('-3 days')) {
     // three days ago or more
}

But here is the DateTime example for the sake of completeness.

$userTimestamp = new DateTime('@'.$user_timestamp);
$threeDaysAgo  = new DateTime('-3 days');
if ($userTimestamp < $threeDaysAgo) {
     // three days ago or more
}
John Conde
  • 217,595
  • 99
  • 455
  • 496
  • Can you please elaborate how this works. I just tested the strtotime() example and it did not work. Note that I have timestamp stored in '$user_timestamp' -- EDIT: It may be that your condition is incorrect, should it be *less then*, rather than *greater then*...? – Henrik Petterson Jan 22 '15 at 16:15
  • You are correct. I had my logic backwards. Give that a shot and see if that resolves the issue. – John Conde Jan 22 '15 at 16:18
  • Works fine my friend. I have one final question. Is there any difference in going with either approach in terms of performance? – Henrik Petterson Jan 22 '15 at 16:20
  • 1
    Both will be fast. DateTime is better at handling timezones and DST but for a basic comparison like this the first example should suffice. – John Conde Jan 22 '15 at 16:23
1

No need to convert it or use another function. 3 days = 259200 seconds, so this should work:

if( $user_timestamp < ( $current_timestamp-259200 ) ){
Nathan
  • 366
  • 1
  • 6
  • This is actually a surprisingly simple approach and great for micro-optimisation. – Henrik Petterson Jan 22 '15 at 16:21
  • Just keep in mind that this occurs at the expense of readability. 259200 means what exactly? You'll be hard pressed to find anyone who knows off of the top of their head what the value represents. – John Conde Jan 22 '15 at 16:24
  • Very true, I did have to look it up. Normally I include a comment along the lines of `// 259200 = 3 days ` – Nathan Jan 22 '15 at 16:43