- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎10-24-2023 10:45 PM
Hi Team,
I wanted a field in user table where it contains the user last login in days.
Example if user has not logged in for past 10 days, the int 10 must be visible in the field as value.
Kindly help how to code.
Solved! Go to Solution.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎10-24-2023 11:22 PM
Hi @Preethi26
Yes if you'd like to execute the script in a frequency, just use the Schedule Job.
If you're looking for one time execution, you can leverage the Fix Script.
Sample below. (I assume you're updating the duration field in same record)
var gdtToday = new GlideDateTime();
var grUser = new GlideRecord('sys_user');
grUser.addEncodedQuery(<your_encoded_query>);
grUser.query();
while(grUser.next()){
var gdtLogin = new GlideDateTime(grUser.last_login_time);
var duration = GlideDateTime.subtract(gdtLogin, gdtToday);
grUser.setValue('<field_name>', duration);
grUser.update();
}
Cheers,
Tai Vu

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎10-24-2023 11:26 PM
Hi,
If you want a specific field to have an accurate value, showing the number of days since last login, you will need either to have a calculated field, or some logic that refreshes the value every day.
Consider this scenario.
A user has last logged in on 2023-10-20, and today it's the 2023-10-25, so the correct value should be 5.
But tomorrow, the field will still have the value of 5, which is incorrect, it should be 6.
So the value must be set on a daily basis, or calculated at load/view time.
Do you really want to create some script that loops through all users and sets this value every day (night) ?
In my opinion, it seems excessive, since you already have a date value for the last login time.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎10-24-2023 11:34 PM
It's true, make more sense! You can also leverage the Calculated Value in Dictionary.
(function calculatedFieldValue(current) {
var gdtToday = new GlideDateTime();
var gdtLogin = new GlideDateTime(current.last_login_time);
var duration = GlideDateTime.subtract(gdtLogin, gdtToday);
return duration;
})(current);
Cheers,
Tai Vu