- 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:00 PM - edited 10-24-2023 11:04 PM
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());
Let me know if it works for you.
Cheers,
Tai Vu
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
10-24-2023 11:11 PM
@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?
- 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:27 PM
Thank You.
I will update days apart following same format.