How to calculate "Last login date/time"

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
gimpact
Forum Commoner
Posts: 65
Joined: Tue Jun 16, 2009 11:08 pm

How to calculate "Last login date/time"

Post by gimpact »

Hi,

I have made a simple member script. I would like to add "Last login date" to my script. I am at the moment using gmdate() function to get the current date.

I was thinking instate of just displaying the last login date from the database, i guess people would prefer if i could tell them that "Last login today or last login yesterday or last login 17th Nov, 2009"

Does any one knows how to subtract current date from the "last login date" to calculate how many days ago the user last logged in?

I am doing this for the first time, I could as well be wrong in my whole thinking....! :-)

Thank you,
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: How to calculate "Last login date/time"

Post by Jonah Bron »

Strtotime() is probably what you are looking for. Use it on the date in the DB, and subtract that from the results of time(). That will give you the amount of time since the last login in seconds.

You can then write a function that does a lot of division by 60s and 24s, to figure out a textual representation of that.
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: How to calculate "Last login date/time"

Post by califdon »

You can do even more, and without doing the clumsy arithmetic, which can get you in trouble, as it recently did me, when I unthinkingly compared dates based on midnight times, and when Daylight Saving Time changed, my logic was screwed! The strtotime() function accepts almost any reasonable English date/time expressions, like "yesterday". Try the following little test:

Code: Select all

<?php
echo date('M-j-Y h:i:s',strtotime('next Tuesday'))."<br>".date('M-j-Y h:i:s',strtotime('yesterday'));
?>
 
Post Reply