Expand my Community achievements bar.

How do you calculate difference in time (hours and minutes) between 2 two date/time fields?

Avatar

Level 1

Have trouble creating formula using FormCalc that will calculate difference in time (hours and minutes) from a Start Date/Time field and End Date/Time field. 

I am using to automatically calculate total time in hours and minutes only of an equipment outage based on a user entered start date and time and end date and time. 

For example a user enters start date/time of an equipment outage as 14-Oct-12 08:12 AM and then enters an end date/time of the outage of 15-Oct-12 01:48 PM.  I need a return that automatically calculates total time in hours and minutes of the equipment outage.

Thanks Chris

1 Reply

Avatar

Level 10

Hi,

In JavaScript you could do something like;

var DateTimeRegex = /(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d)/;

var d1 = DateTimeRegex.exec(DateTimeField1.rawValue);

if (d1 !== null)

{

    var fromDate = new Date(d1[1], d1[2]-1, d1[3], d1[4], d1[5]);

}

var d2 = DateTimeRegex.exec(DateTimeField2.rawValue);

if (d2 !== null)

{

    var toDate = new Date(d2[1], d2[2]-1, d2[3], d2[4], d2[5]);

}

const millisecondsPerMinute = 1000 * 60;

const millisecondsPerHour = millisecondsPerMinute * 60;

const millisecondsPerDay = millisecondsPerHour * 24;

var interval = toDate.getTime() - fromDate.getTime();

var days = Math.floor(interval / millisecondsPerDay );

interval = interval - (days * millisecondsPerDay );

var hours = Math.floor(interval / millisecondsPerHour );

interval = interval - (hours * millisecondsPerHour );

var minutes = Math.floor(interval / millisecondsPerMinute );

console.println(days + " days, " + hours + " hours, " + minutes + " minutes");

This assumes that the values in DateTimeField1 and DateTimeField2 are valid, which means the rawValue will be in a format like 2009-03-15T18:15

Regards

Bruce