Jaissica1
Tera Explorer
Options
- Post History
- Subscribe to RSS Feed
- Mark as New
- Mark as Read
- Bookmark
- Subscribe
- Printer Friendly Page
- Report Inappropriate Content
on 08-25-2021 09:32 AM
Hi everyone!
I recently had a requirement to round up a duration field to the nearest 30 minutes, relative to another field, e.g.:
Field A | Field B |
1h 22m | 1h 30m |
1h 45m | 2h |
3h | 3h |
The code below will accomplish this:
// Run on the server side e.g. Business Rule
(function executeRule(current, previous /*null when async*/) {
var time = current.time_worked.dateNumericValue(); //grab the GlideDateTime field A
var time_hours = time / (60 * 60 * 1000); //convert miliseconds to hours
var decimal = time_hours - Math.floor(time_hours); //extract the decimals in the hours
var newdecimal = 0;
if (decimal == 0) { //rounded number - no action needed
newdecimal = 0;
} else if (decimal > 0 && decimal <= 0.5) { //minutes under 30, then round up to 30
newdecimal = 0.5;
} else {
newdecimal = 1; // minutes above 30, then round up to hour
}
//convert hours to miliseconds
var newTime = (Math.floor(time_hours) + newdecimal) * (60 * 60 * 1000);
//convert miliseconds to GlideDateTime format
var gdt = new GlideDateTime();
gdt.setNumericValue(newTime);
//populate the field B with the rounded up time
current.setValue('u_chargeable_time_worked', gdt.getValue());
})(current, previous);
The code is executed on the server side, for example, Business Rule.
By simply breaking down the if statement in more decimals, such as 0 -> 0.25 -> 0.5 -> 0.75 -> 1, you can adapt the code to other intervals, such as 15 minutes.
If you have any suggestions for improvements to the code, please share them.
Thank you!
- 1,476 Views
Comments

Andrew Bettcher
Kilo Sage
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
06-22-2022
05:47 AM
I did have to change it slightly to get it to round to 15 minutes intervals but your code was easy enough to follow so it wasn't hard. Thank you so much.