web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Dynamics 365 Community / Blogs / Power Melange / How to find difference betw...

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

PowerMelangeByShalinee Profile Picture PowerMelangeByShalinee 70

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");
        } 
		else 
		{
            endDateFieldControl.clearNotification("EndDate");            
			var date1 = new Date(startDate);
            var date2 = new Date(endDate);
            var duration = (date2 - date1) / 60000;
           formContext.getAttribute("pm_duration").setValue(duration);
        }
    }
}

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.


This was originally posted here.

Comments

*This post is locked for comments