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
https://forums.phpfreaks.com/topic/258509-subtracting-two-unix-timestamps/
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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.