Displaying user last login like "3 days, 2 hours ago"

Discussion in 'Databases' started by Kendothpro, Apr 10, 2007.

  1. #1
    I have a table "user" with a field "lastlogin" that stores a basic datetime of the last time the user logged in
    Do you know of a fast function or class that can convert that field into a more readable "User last logged in: 3 days, 2 hours ago" or something similar?
    I've seen this everywhere and I don't like reinventing the wheel


    Also, to track which users are online
    I'm currently using a custom-made login class that basically sends a REPLACE INTO online_user SET id=$userid every time a page with a registered session is loaded

    Is there a better way to log online users? sending a query on every pageview just doesn't seem right to me
     
    Kendothpro, Apr 10, 2007 IP
  2. druidelder

    druidelder Peon

    Messages:
    285
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    0
    #2
    I had this really long answer to your last questions, but then I realized I was answering a totally different question. I assume you are using PHP. I don't know the code in PHP, but you can also use the session variable to track this data. I can't say which would be more efficient in PHP, but that is where to start.

    The first question:

    'User last logged in ' + DateDiff(date1,date2) + ' days, ' + Hour(TimeDiff(Time(date1), Time(date2))) + ' hours ago'

    Something along those lines. DateDiff() gives the difference in days between two dates. TimeDiff() give the difference in time between to time or datetime fields. Time() extracts the time portion of a datetime. The reason for using this is that if you use TimeDiff() with the whole date then you will get hours above 23 (two dates almost two days apart would show a timediff of 46 hours or so, by eliminating the date, the time is the only thing to compare). Hour will give you just the hour portion of the result from TimeDiff().
     
    druidelder, Apr 10, 2007 IP
  3. Kendothpro

    Kendothpro Well-Known Member

    Messages:
    574
    Likes Received:
    25
    Best Answers:
    0
    Trophy Points:
    120
    #3
    Very nice, thanks :)
     
    Kendothpro, Apr 11, 2007 IP
  4. druidelder

    druidelder Peon

    Messages:
    285
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    0
    #4
    I forgot to mention that the code I supplied is actually SQL. So you would not write what I posted exactly. It would be more like:

    Select DateDiff(lastLogin, Now()) AS 'Days', Hour(TimeDiff(Time(lastLogin), Time(Now()))) AS 'Hours' FROM tblUsers where tblUsers.userID = @userID

    I just thought I would clarify that for others coming to read this post later.
     
    druidelder, Apr 11, 2007 IP