htmanning has asked for the wisdom of the Perl Monks concerning the following question:

Monks, I'm trying to write an indicator for when a user is on a website. I'm trying to insert a timestamp into the database when they refresh a page, then have a script subtract the timestamp from the current time. If it's within 5 minutes, I'll indicate they are online.

How to I generate a timestamp that I can subtract from? Make sense?

I'm currently stuffing the current date and time into the database. I can use an amateur's way of converting that time to military time, then trying to subtract but there has to be an easier way.

Thanks.

  • Comment on Using Timestamp to tell if someone is on the site

Replies are listed 'Best First'.
Re: Using Timestamp to tell if someone is on the site
by huck (Prior) on Jan 05, 2017 at 04:22 UTC

    How about just unformatted time. ie

    my $lasttime=from_db($userid); my $thistime=time; if ($thistime-$lasttime<(5*60)) { print 'online'."\n"; } set_db($userid,$thistime);

      Thank you, I figured it out although not as clean as you did. I inserted the date and time into separate database fields. I then split the lastvisittime and multiplied the hour by 60. I added that number to the minutes to get a time in minutes. I did the same for the current time, then subtracted the last visit from now. Thanks.

        What if the last visit was at 23:59, and now is 00:01? The difference is negative which is less than 5 and says online and is right

        But what if the last visit was at 22:59, and now is 00:01? The difference is again negative which is less than 5 and says online, but wrong since it was more than 5 min ago

        Consider calculating the time difference when you select the record. For example in MySQL

        SELECT TIMESTAMPDIFF(SECOND,lastvisit,NOW()) FROM table

        Change SECOND to MINUTE as required.

        poj
Re: Using Timestamp to tell if someone is on the site
by haukex (Archbishop) on Jan 05, 2017 at 10:34 UTC

    Hi htmanning,

    I often recommend something like DateTime for such calculations, but since in this case you're just subtracting two times to tell if they're more or less than 5 minutes apart and you probably don't need high precision, probably the easiest way is with UNIX timestamps, as huck suggested. In Perl, you can use time to get seconds since the epoch (which on most systems is January 1, 1970, 00:00:00 UTC), and depending on the format of the database column, you can either have the database convert that to a UNIX timestamp, e.g. MySQL has the function UNIX_TIMESTAMP(date), or, if you've stored it in the database as a string, you can use Time::Piece::strptime, POSIX::strptime, or DateTime::Format::Strptime to parse it back into seconds since the epoch - just don't forget to take time zones into account. Then, it's just a simple matter of subtraction of the two values.

    Hope this helps,
    -- Hauke D