How to configure a catalog client scripts for the duration of two dates on catalog item?

A Icen
Tera Expert

hi everyone, 

I have a catolog item in which the duration time difference is calculated and populated when start and end date are picked up. I need a catalog client scripts, I have attached the screen to give you an idea what I need exactly. 

Thanks 

1 ACCEPTED SOLUTION

Hi 

The previous code did not work. 

I have configured the code below, and it worked as I did want. Just keep in mind that use this code for both start date and end date on variable (not duration)

function onChange(control, oldValue, newValue, isLoading) {
    // Get the values of start_date and end_date fields


    // Check if both fromDate and toDate have valid values
    if (g_form.getValue('start_date') && g_form.getValue('end_date')) {
    var fromDate = g_form.getValue('start_date');
    var fromDateValues = fromDate.split('/');
   
    var toDate = g_form.getValue('end_date');
    var toDateValues = toDate.split('/');
        // Create Date objects for start_date and end_date
        var fromDateObj = new Date(fromDateValues[2], fromDateValues[1], fromDateValues[0]);
        var toDateObj = new Date(toDateValues[2], toDateValues[1], toDateValues[0]);

        // Calculate the difference in milliseconds
        var timeDifference = toDateObj.getTime() - fromDateObj.getTime();
       
        // Convert milliseconds to days
        var daysDifference = timeDifference / (1000 * 3600 * 24);
       
        // Round the result to get the total number of days
        var totalDays = Math.round(daysDifference);

        // Set the value of the 'duration' field
        g_form.setValue('duration', totalDays);
    }
}

View solution in original post

10 REPLIES 10

kkrushkov
Mega Sage

Hello, 

You can try this script but consider refactoring it to match your field values.

 

    var fromDate = g_form.getValue('start_date');
    var toDate = g_form.getValue('end_date');
    var fromDateObj = new Date(fromDate);
    var toDateObj = new Date(toDate);

    var timeDifference = toDateObj.getTime() - fromDateObj.getTime();
    var daysDifference = timeDifference / (1000 * 3600 * 24);
    var totalDays = Math.round(daysDifference);
    g_form.setValue('duration', totalDays);

Ankur Bawiskar
Tera Patron
Tera Patron

@A Icen 

this should be a simple one. what did you start with and where are you stuck?

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

Hi Ankur,
I have typed this on catalog client scripts as @kkrushkov suggested me. However, it does not calculate and populate the time  difference on the "duration" filed. (as it is in the picture I have attached)

Hello, @A Icen 

You need to set a variable name here, such as the end date. Additionally, if you test it in the Service Portal, change the UI Type to All.

kkrushkov_0-1711684687942.png