function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sindoorasindoora 

Apex code to get last login date of users

how to capture the last login date of a user into a custom field

Satish_SFDCSatish_SFDC
Through a formula this might not be possible but you will have to write an soql query for this.

This is the query you will have to use

User u = [SELECT LastLoginDate FROM User WHERE Id =:UserInfo.getUserId()];

Hope this helps.

Regards,
Satish Kumar
Please mark my answer as a solution if it was helpful so it is available to others as a proper solution.
If you felt I went above and beyond, please give me Kudos by clicking on the star icon.
Subramani_SFDCSubramani_SFDC
Hi,

public DateTime lastlogin{get;set;}

controller:
User u = [SELECT LastLoginDate FROM User WHERE Id =:UserInfo.getUserId()];
lastlogin = u.LastLoginDate;


VF: {! lastlogin }
sindoorasindoora

Thank you for resopnse.Can i use this as a trigger?

Satish_SFDCSatish_SFDC
No it should be on a VF page.
If you have it on a trigger, it would only refresh if there are any updates to the record.

Regards,
Satish Kumar
sindoorasindoora

But My requirement is only trigger or Apec not supposed for vf

sindoorasindoora
trigger lastloginDate on User (before update) {


User u = [SELECT LastLoginDate FROM User WHERE Id =:UserInfo.getUserId()];
trigger.new[0].Custom_LastLogin__c = u.LastLoginDate;

}
The above code i'm using but this works only if a page is refreshed. can u suggest any alternate like how to use after update login.I tried that but is fired back
Becky MillerBecky Miller
How would you do this on a Visualforce Page.  I need to do the same thing I need a count of how many days a user has not logged in.  This number would be used for Adoption Dashboards.  So, I need NOW() - Lastlogindate.  Not sure how we go about this.   Did you ever get a solution?