Get the last login time as number

Preethi26
Tera Contributor

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.

1 ACCEPTED SOLUTION

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

View solution in original post

6 REPLIES 6

OlaN
Giga Sage
Giga Sage

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.

@Preethi26 

It's true, make more sense! You can also leverage the Calculated Value in Dictionary.

Screenshot 2023-10-25 at 13.33.18.png

(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