Microsoft InfoPath 2010
The official blog of the Microsoft InfoPath team

Calculating Elapsed Time…without code!

Calculating Elapsed Time…without code!

Rate This
  • Comments 59

UPDATE: Due to the number of requests for adding more columns to this sample, I have re-designed the sample. If I have time in the future I will update the steps to create this new design; however, for now you can download the updated design here to see the changes. The expressions are very similar to the original design but I now use a repeating table for entering "break" times so you can have as many as you need! 

How many times have you needed to calculate the difference between time entries…only to find out the only way to accomplish this was to write custom code? Well no more! If your time entries will not cross days, then you can use a number of functions and expressions to parse the entered times and calculate the difference. In the sample below we will show you the types of expressions that are needed for these calculations to work – I would encourage you to first create this sample as documented as the expressions are not for the “faint of heart!” :-)

Note: if you choose to copy/paste the expressions for this sample, you will use the Default Value box for each field and after clicking the “fx” button, be sure to also enable the “Exit XPath” option before you paste these expressions.

If you'd like to take a look at the completed version of this sample, here is the .xsn file - make sure to save it locally before opening it.

Create the data structure

1) Add a Repeating Table to your View with 4 columns

2) Rename the fields and specify the data types as follows, from left to right:

Name Data Type
myDate Date (date), Format: *3/14/2001
StartTime Time (time), Format: *9:46 AM
EndTime Time (time), Format: *9:46 AM
ActualTime Text (string)

3) Change the first field in the table to a Date Picker control

 
4)  Add 2 additional fields to the Repeating Group node (these will not be shown on the view – they are used to aid in the calculations)

Name Data Type
ElapsedTime Text (string)
TotalMinutes Decimal (double)


5) Add one final field to calculate the sum of all the entries – this should be added to the myFields node…not the Repeating node

Name Data Type
TotalTime Text (string)

Your final data structure should look like this:

And your form could look like this:

 

Adding the expressions…let the fun begin!

The first step is to convert the StartTime and EndTime values to minutes – this makes the calculation a bit easier. In addition, we don’t want to execute this calculation if either the StartTime or EndTime is blank. So to perform this “conditional statement”, we’ll use the logic explained in this blog entry.

Step 1: Parse the Hours and Minutes

1) We first need to parse the “hours” and convert this to minutes by multiplying that value by 60. To do this we will use the “substring-before” function to look for the colon (“:”) in the time field and extract the value before the colon:

substring-before(../my:EndTime, ":") * 60)
substring-before(../my:StartTime, ":") * 60

2) To each of these values, we need to add the minutes that were entered after the colon. Now when time values are stored in the underlying XML, they are stored in this manner: hh:mm:ss. So to pull just the minutes entered, we will use a combination of the “substring-before” and “substring-after” functions since we need the value entered “after” the first colon and “before” the last colon:

substring-before(substring-after(../my:EndTime, ":"), ":")
substring-before(substring-after(../my:StartTime, ":"), ":")

3) Now, at this point we could place each of these expressions together to get the total hours and minutes for each time entry:

((substring-before(../my:EndTime, ":") * 60) + substring-before(substring-after(../my:EndTime, ":"), ":"))
((substring-before(../my:StartTime, ":") * 60) + substring-before(substring-after(../my:StartTime, ":"), ":"))

4) Keep in mind, we don’t want this expression to execute if either the StartTime or EndTime fields are empty and we also need to subtract the StartTime total minutes from the EndTime total minutes. So to do this we will use the “substring” function in conjunction with a “condition.” The substring function has the following signature:

substring([String Value], [Starting Position], [Condition/Length])

To incorporate our expressions into the substring function, it would look like this:

Substring([EndTime – StartTime], 1, EndTime != “” and StartTime != “”)

EndTime expression:

((substring-before(../my:EndTime, ":") * 60) + substring-before(substring-after(../my:EndTime, ":"), ":"))

StartTime expression:

((substring-before(../my:StartTime, ":") * 60) + substring-before(substring-after(../my:StartTime, ":"), ":"))

Starting position: 1

Condition expression (that if true, evaluates to the length of what we want to return so we use the “string-length” function to get the length of our initial expression):

(../my:StartTime != "" and ../my:EndTime != "") * string-length(((substring-before(../my:EndTime, ":") * 60) + substring-before(substring-after(../my:EndTime, ":"), ":")) - ((substring-before(../my:StartTime, ":") * 60) + substring-before(substring-after(../my:StartTime, ":"), ":")))

So our final expression for the TotalMinutes field would look like this:

substring(((substring-before(../my:EndTime, ":") * 60) + substring-before(substring-after(../my:EndTime, ":"), ":")) - ((substring-before(../my:StartTime, ":") * 60) + substring-before(substring-after(../my:StartTime, ":"), ":")), 1, (../my:StartTime != "" and ../my:EndTime != "") * string-length(((substring-before(../my:EndTime, ":") * 60) + substring-before(substring-after(../my:EndTime, ":"), ":")) - ((substring-before(../my:StartTime, ":") * 60) + substring-before(substring-after(../my:StartTime, ":"), ":"))))

 

 

Step 2: Convert resulting Total Minutes to hours and minutes

This expression will use the same basic logic we used above: first divide the resulting total minutes field by 60 to see how many hours have elapsed. If the result of that division contains a decimal point (i.e. 90 minutes / 60 = 1.5) then parse the value before the decimal point (for the hours) and then use the “mod” function to return the balance of the minutes.

1) We need to divide the TotalMinutes field by 60 to get how many hours have elapsed; however, we also need to check if the resulting value contains the decimal point. So the first expression will use the “substring” function so we can incorporate the conditional test. For the conditional test, we will use the “contains” function to see if the result contains the decimal point:

contains(../my:TotalMinutes div 60, ".")

So our initial expression would be as follows: this incorporates the “concat” function so if the resulting value contains a decimal point, we will parse that value, concatenate a colon and the concatenate the result of TotalMinutes mod 60:

substring(concat(substring-before(../my:TotalMinutes div 60, "."), ":", ../my:TotalMinutes mod 60), 1, contains(../my:TotalMinutes div 60, ".") * string-length(concat(substring-before(../my:TotalMinutes div 60, "."), ":", ../my:TotalMinutes mod 60)))

2) If the resulting expression does not contain a decimal point, then we will simply concatenate a colon with the results of TotalMinutes mod 60:

substring(concat(../my:TotalMinutes div 60, ":", ../my:TotalMinutes mod 60), 1, not(contains(../my:TotalMinutes div 60, ".")) * string-length(concat(../my:TotalMinutes div 60, ":", ../my:TotalMinutes mod 60)))

3) So our final expression for the ElapsedTime field would be as follows:

concat(substring(concat(substring-before(../my:TotalMinutes div 60, "."), ":", ../my:TotalMinutes mod 60), 1, contains(../my:TotalMinutes div 60, ".") * string-length(concat(substring-before(../my:TotalMinutes div 60, "."), ":", ../my:TotalMinutes mod 60))), substring(concat(../my:TotalMinutes div 60, ":", ../my:TotalMinutes mod 60), 1, not(contains(../my:TotalMinutes div 60, ".")) * string-length(concat(../my:TotalMinutes div 60, ":", ../my:TotalMinutes mod 60))))

 

 

Step 3: Final Formatting - the ActualTime field

The way the expression is written for the ElapsedTime field, if the resulting minutes is less than 10, only a single value will be returned (i.e. 0:9). Because of this, we want to test for this condition and if the minutes are less than 10, then concatenate a zero (“0”) before that value so the time appears correct. Now this expression could possibly have been incorporated into the ElapsedTime expression but for ease and clarity, I separated these two steps into different fields.

This expression uses the “string-length” function to determine the length of the string after the colon. If the length is 2 (minutes are greater than 9) then simply concatenate the hours, a colon and the minutes. However, if the length is 1 (minutes are less than 10) then concatenate the hours, a colon with a zero (“:0”) and the minutes. Like before, we will use the “substring” function with a condition statement to determine what to return:

concat(substring(concat(substring-before(../my:ElapsedTime, ":"), ":", substring-after(../my:ElapsedTime, ":")), 1, (string-length(substring-after(../my:ElapsedTime, ":")) = 2) * string-length(concat(substring-before(../my:ElapsedTime, ":"), ":", substring-after(../my:ElapsedTime, ":")))), substring(concat(substring-before(../my:ElapsedTime, ":"), ":0", substring-after(../my:ElapsedTime, ":")), 1, (string-length(substring-after(../my:ElapsedTime, ":")) = 1) * string-length(concat(substring-before(../my:ElapsedTime, ":"), ":0", substring-after(../my:ElapsedTime, ":")))))

Step 4: Create the TotalTime expression for keeping a running total of the elapsed time

The last step is to create the TotalTime expression – this is similar to the ActualTime expression except we now incorporate the “sum” function to get the running total:

concat(substring(concat((sum(../my:group1/my:group2/my:TotalMinutes) - sum(../my:group1/my:group2/my:TotalMinutes) mod 60) div 60, ":", sum(../my:group1/my:group2/my:TotalMinutes) mod 60), 1, (sum(../my:group1/my:group2/my:TotalMinutes) mod 60 > 9) * string-length(concat((sum(../my:group1/my:group2/my:TotalMinutes) - sum(../my:group1/my:group2/my:TotalMinutes) mod 60) div 60, ":", sum(../my:group1/my:group2/my:TotalMinutes) mod 60))), substring(concat((sum(../my:group1/my:group2/my:TotalMinutes) - sum(../my:group1/my:group2/my:TotalMinutes) mod 60) div 60, ":0", sum(../my:group1/my:group2/my:TotalMinutes) mod 60), 1, (sum(../my:group1/my:group2/my:TotalMinutes) mod 60 < 10) * string-length(concat((sum(../my:group1/my:group2/my:TotalMinutes) - sum(../my:group1/my:group2/my:TotalMinutes) mod 60) div 60, ":0", sum(../my:group1/my:group2/my:TotalMinutes) mod 60))))

Step 5: Test!
Enter a Start and End Time in the form of: h:mm AM(PM), such as: 8:00 AM and 5:00 PM – the ActualTime field should display the difference (as 9:00) and if you continue adding rows, the TotalTime field should reflect the running total.

This functionality allows you to create elapsed time scenarios that work in both client and browser forms without writing one line of code!

Scott Heim
Support Engineer

Attachment: ElapsedTime_NoCode_NewDesign.xsn
Leave a Comment
  • Please add 2 and 4 and type the answer here:
  • Post
  • This is wonderful, and is exactly what I needed.  I have made a few modifications on it to customize it to my needs, and it is working perfectly.  However, with the addition of the new break time in the last segment, it will no longer just calculate time in and time out (if the employee doesn't take a lunch that day).  I am feverishly learning xpath, but I am getting tied into knots on the math.  Which part do I need to add/subtract to leave the break time optional so the other fields will add up on their own?  Also, what if there is an "other" time in/out that needs to be calculated for events such as travel?  You guys are great in this forum, and has added tremendous tool to my InfoPath programming!

  • Hi mcmurrayjl,

    Let me start with your 2nd question:

    - "What if there are other time in/out needs?"

    > In this case, I would suggest you look at changing the design to make it more "relational" - for example: "1 day can have 0 or more time in/out entries." Basically it would be a 1->many design. To stay with the design shown here in this sample would be difficult at best.

    - "How can I get this sample to calculate the elapsed time with or without the break time being entered?"

    > Ok - so this gets a little more involved and I think the best way to answer this is to first show how I arrive at the final expression for the "TotalMinutes" node.

    Let's begin by breaking down each part of the expression:

    - Part 1: Calculate the difference between only the start and end times entered:

    (((substring-before(../my:EndTime, ":") * 60) + substring-before(substring-after(../my:EndTime, ":"), ":")) - ((substring-before(../my:StartTime, ":") * 60) + substring-before(substring-after(../my:StartTime, ":"), ":")))

    - Part 2: Calculate the difference between only the start and end "break times" entered:

    (((substring-before(../my:EndBreakTime, ":") * 60) + substring-before(substring-after(../my:EndBreakTime, ":"), ":")) - ((substring-before(../my:StartBreakTime, ":") * 60) + substring-before(substring-after(../my:StartBreakTime, ":"), ":")))

    So at this point, you could replace the expression in the TotalMinutes node with either of these above and they would produce the expected results.

    Now, let's bring the 2 parts above together so we are basically at where you are now - needing all fields completed:

    (((substring-before(../my:EndTime, ":") * 60) + substring-before(substring-after(../my:EndTime, ":"), ":")) - ((substring-before(../my:StartTime, ":") * 60) + substring-before(substring-after(../my:StartTime, ":"), ":"))) - (((substring-before(../my:EndBreakTime, ":") * 60) + substring-before(substring-after(../my:EndBreakTime, ":"), ":")) - ((substring-before(../my:StartBreakTime, ":") * 60) + substring-before(substring-after(../my:StartBreakTime, ":"), ":")))

    As you know, at this point you need both the start/end times and the start/end "break" times entered. So how do we modify this to calculate regardless of whether someone entered start/end "break" times. This is where the logic comes in from the link I referenced in the original post to provide us with "if, then, else" logic.

    The expression that we use for this is as follows:

    concat(

    substring(TrueResult, 1, (BoolCondition) * string-length(TrueResult)),

    substring(ElseResult, 1, (not(BoolCondition)) * string-length(ElseResult)))

    In other words, "concat" followed by a substring expression for the "true" result then a comma followed by an expression for the "false" result.

    So if the start/end "break" times are filled in by the user, then we know our "true" result is the expression above that works now. The "boolean" condition we will use is as follows for the "true" result:

    (../my:StartBreakTime != "" and ../my:EndBreakTime != "")

    In other words, StartBreakTime and EndBreakTime are not blank.

    The "else" portion of our "concat" statement is when the StartBreakTime and EndBreakTime are blank - so the "boolean" condition would be as follows for the "false" result:

    (../my:StartBreakTime = "" and ../my:EndBreakTime = "")

    And when this is the scenario (no break times entered) we only need to calculate the difference between the start and end times, which was our "Part 1" noted above.

    So now that we have all the pieces of the expression, le's put it together:

    concat(substring((((substring-before(../my:EndTime, ":") * 60) + substring-before(substring-after(../my:EndTime, ":"), ":")) - ((substring-before(../my:StartTime, ":") * 60) + substring-before(substring-after(../my:StartTime, ":"), ":"))) - (((substring-before(../my:EndBreakTime, ":") * 60) + substring-before(substring-after(../my:EndBreakTime, ":"), ":")) - ((substring-before(../my:StartBreakTime, ":") * 60) + substring-before(substring-after(../my:StartBreakTime, ":"), ":"))), 1, (../my:StartBreakTime != "" and ../my:EndBreakTime != "") * string-length((((substring-before(../my:EndTime, ":") * 60) + substring-before(substring-after(../my:EndTime, ":"), ":")) - ((substring-before(../my:StartTime, ":") * 60) + substring-before(substring-after(../my:StartTime, ":"), ":"))) - (((substring-before(../my:EndBreakTime, ":") * 60) + substring-before(substring-after(../my:EndBreakTime, ":"), ":")) - ((substring-before(../my:StartBreakTime, ":") * 60) + substring-before(substring-after(../my:StartBreakTime, ":"), ":"))))), substring((((substring-before(../my:EndTime, ":") * 60) + substring-before(substring-after(../my:EndTime, ":"), ":")) - ((substring-before(../my:StartTime, ":") * 60) + substring-before(substring-after(../my:StartTime, ":"), ":"))), 1, (../my:StartBreakTime = "" and ../my:EndBreakTime = "") * string-length((((substring-before(../my:EndTime, ":") * 60) + substring-before(substring-after(../my:EndTime, ":"), ":")) - ((substring-before(../my:StartTime, ":") * 60) + substring-before(substring-after(../my:StartTime, ":"), ":"))))))

    I hope this helps!

    Scott

  • Scott, let me start by saying YOU ARE THE MAN.  Not only did you answer the question, you broke it down so I could understand how each piece relates to the puzzle.  This is beyond what I expected, and definately put me miles down the road.  I don't know where you work, but you deserve a raise and a promotion.  I think these xpath expressions are pretty slick, and am looking to add more functionality to my existing forms with these methods.  It is a bit confusing at first, but hopefully I will know at least 25% of what you do, and I will be happy!!  Thanks again Scott!

  • Scott,

    Thank you very much for responding to my inquiry about adding break time columns to your sample.  That worked wonderfully.  The previous posting you supplied to “mcmurrayjl” is also intriguing to me.  

    Let’s say I too wanted to have two additional columns for other time taken off.  You said that staying with the current design shown in the sample would be difficult at best.  I’m pretty good building forms through the GUI of InfoPath but I don’t have much experience with C#.  Forgive me if this a stupid question but could I still keep the design you applied and use C# code to write the other two columns?  Or is it best to just start from scratch and do the whole thing in C#?  I just didn’t know if it were possible to incorporate both xPath expressions and C# in the same repeating table.

    Thank you for your information and codesmanship!!! It has been very helpful.

  • Thanks  mcmurrayjl!

    Brooks1856 - let me clarify my comments: if you were only going to add another 1-2 columns, then you could probably stay with this design. However, if you have a situation where you could protentially have multiple "time in and time out" entreies, then a better design is a relational one where , say, each new time in/out would be a new row in a repeating table.

    Now to more address your question: it is important to know that you do not have programmatic access to the controls in an InfoPath Form Template - you only have access to the nodes to which those controls are bound. So you cannot create them dynamically if that is what you were asking. This whole expression though is getting pretty outlandish <g> so another option would be to perform the "elapsed time" calculations in code and simply set the values of the corresponding nodes for the form. When doing this in code, the code would not be anywhere near what you have to do in this expression - but the whole point of this sample was how to accomplish this without code.

    Scott

  • Hi All,

    Thanks for an informative post.

    I hope I can phrase this question constructively, but, boy, it seems like a ton of trouble to do what is so easy right in Excel VBA. The DateDiff function for example.

    Is there a function library or something we could tap into for this type of basic stuff?

  • Hi bdog,

    Yeah - that would sure be nice wouldn't it? <G>

    Unfortunately no; however, this post was meant as a way to demonstrate how to accomplish an "elapsed time" calculation without any code. If one was comfortable using code, then this would be a bit more "cleaner" - at least from an expression point of view.

    Scott

  • I give up!!!!  How in blue blazes do you add one more set of columns (other time in & Out)  I have been banging my head on my keyboard for a week now.  Any information would be appreciated.  "infopath" - I'll send you something to your PayPal account!  :)

  • Cue thunderbolts and lightning. I figured that &quot;Infopath timesheet, no problem!&quot; and &quot;there

  • Hi everyone,

    So there seems to be some interest <g> in having a sample that allows for one or more "break time" types of entries. I am in the process of re-designing the sample to you do not have to update the expressions each time.

    I am hoping to have this done within the next few days but I am not sure yet if it will get posted here or as a new blog post...I will let you know if it comes as a new post.

    Thanks everyone!

    Scott

  • I noticed that your solution (which is great) uses "div" and "mod". I couldn't find any mention of them in the documentation. Are there other undocumented operators?

    Thanks,

    Chris

  • Hi ChrisBacon,

    Thanks!

    The "div" operator is simply "division" - which in XML is "div." When you choose to "Show the XPath" we show you the actual operator we are using. So: 10 / 5 is the same as: 10 div 5.

    For the "mod" operator you can find some information in the Help file for InfoPath - in the Developer reference. The short answer: "mod" returns the modulus — that is, divides num1 by num2, returning the remainder.

    Scott

  • Hi Scott,

    This info was GREAT and helped me a lot.  New to InfoPath and weak in coding.  I have another question.  Your basic design works great for our needs and I would like to add a couple of fields.  

    One for required hours that would be entered by the user (changes per pay period) and another for used annual/sick time.  I would like to keep these fields consistant in how they are entered with  the other fileds in your form. It does not have to calculate anything as this will be done by the user.  Each day may use sick and annual on the same day.  I have these fields in a separte repeating table.  I would also like a sum of the sick/annual fields at the end.  Is this possible using the same time code you used above?  Thanks for you help.

  • Hi bmorri5,

    I am not sure I exactly follow what you need but in theory, this should be doable. However, I am creating a new design for this sample that allows the user to enter as many "break" times as needed. This should make the process easier in general and for you as well.

    I am hoping to get this new design posted in a few days - you may want to wait to see this and see if it helps with what you need.

    Scott

  • Scott,

    THANK YOU!!! I will keep checking back!!!!  Thanks again!!

Page 2 of 4 (59 items) 1234