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

Tai Vu
Kilo Patron
Kilo Patron

Hi @Preethi26 

Let's try below script.

 

 

var gr = new GlideRecord('sys_user');
gr.get('f3af54c413651200042ab3173244b053'); //replace your user sys_id for testing

var gdtLogin = new GlideDateTime(gr.last_login_time);
var gdt = new GlideDateTime();

var duration = GlideDateTime.subtract(gdtLogin, gdt);
gs.info(duration.getDisplayValue());
gs.info(duration.getDayPart());

 

Screenshot 2023-10-25 at 13.04.15.png

  

Let me know if it works for you.

 

Cheers,

Tai Vu

Preethi26
Tera Contributor

@Tai Vu Many thanks its working in Background script.

If i want to assign to field should i need to declare variable and assign the duration to it using scheduled Job and run it?

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

Preethi26
Tera Contributor

Thank You.

I will update days apart following same format.