The CreatorCon Call for Content is officially open! Get started here.

Jaissica1
Tera Explorer

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 AField B
1h 22m1h 30m
1h 45m2h
3h3h

 

 find_real_file.png

 

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!

Comments
Andrew Bettcher
Kilo Sage

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.

Version history
Last update:
‎08-25-2021 09:32 AM
Updated by: