How to find difference between two DateTime fields in a Whole Number field with Duration as the Format Type

Business Scenario: We have to calculate the difference between two DateTime fields and store the result in a Whole Number field with the Format Duration to let us know the difference in minutes, hours,days accordingly.

Solution: Before getting into the direct solution, let us briefly know what a Duration Format Whole number field is, as because the solution lies there.

This format option can be used to display a list of duration options. But the data stored in the database is always a number of minutes. Here is the catch- whenever we are filling the data here, we gotta fill it in minutes and the rest will be taken care off.

Lets get into the code now!

function findDuration(eContext) 
    var formContext = eContext.getFormContext();
    var startDate = formContext.getAttribute("pm_startdate").getValue();
    var endDate = formContext.getAttribute("pm_enddate").getValue();
    var endDateFieldControl = formContext.getControl("pm_enddate");
    if (startDate != null && endDate != null) 
        if (startDate > endDate) 
            endDateFieldControl.setNotification("End Date should be greater than Start Date ", "EndDate");
			var date1 = new Date(startDate);
            var date2 = new Date(endDate);
            var duration = (date2 - date1) / 60000;

Explanation: When we subtract two dates, we get the result in milliseconds,thus we have to convert it to minutes and put it in the whole number field which is why we divide it by 60000.[1 millisecond=1/(60*1000) min]. Simple isn’t it.

Lets see it in action

Hope it helps!

& the Power Quote of the day is:

The secret of change is to focus all of your energy not on fighting the old but on building the new.

Author: powershalinee

Techno-Functional Consultant

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: