Jump to content

Subtracting two Unix Timestamps


doubledee

Recommended Posts

Why doesn't this code work...

echo '<p>time() = ' . time() . ' seconds</p>';
echo '<p>$lastActivity = ' . $lastActivity . '</p>';
echo '<p>Seconds Active: ' . time() - $lastActivity . ' seconds</p>';

...where $lastActivity comes from my database.

 

 

When I run my script I see...

time() = 1331187131 seconds

 

$lastActivity = 1331186745

-1331186745 seconds

 

The last line is dropping the label and there is now Date Math?!

 

 

Debbie

 

Link to comment
Share on other sites

Because of Operator Precedence.  The  . (concatenation) and - (subtraction) operators have the same precedence level and are processed from left-to-right, so when php sees that line it does these steps:

 

(assume time() returns 1234567 and $lastActivity contains 654321)

 

  • '<p>Seconds Active: ' . time() 
    • Result: ''<p>Seconds Active: 1234567 '

    [*]''<p>Seconds Active: 1234567 ' - $lastActivity 

    • Result: -654321

    [*] -654321 . ' seconds</p>'   

    • Result: '-654321 seconds</p>'

 

By either enclosing the math operation in parenthesis or moving it out to it's own line and saving the result to a variable, you force that to come first before the concatenation operations.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.