I know this is an old post, but I have seen quite some questions on date calculations and posts to the msdn site, which I looked through and really didn't help me much. So I came up with this, hopefully new people will find it helpful. Simply takes the difference between two date picker boxes in infopath(2003 or 2007). Also it was about time I posted some useful information to this great site.
My two date fields were: StartDate and EndDate, and the difference was saved in DaysOff text box.
I also used an on after event for end date.
VB.net Code (backward compatible with InfoPath 2003):
Imports
Microsoft.VisualBasic.DateAndTime (reference that at the top of the code under: Imports Microsoft.Office.Interop.InfoPath.SemiTrust)
'If StartDate and EndDate is not blank, and End Date is greater than StartDate then calculate difference.
If thisXDocument.DOM.selectSingleNode("/dfs:myFields/my:AbsenceDetails/my:StartDate").text <> "" And _
thisXDocument.DOM.selectSingleNode(
"/dfs:myFields/my:AbsenceDetails/my:EndDate").text <> "" And _System.Convert.ToString(thisXDocument.DOM.selectSingleNode("/dfs:myFields/my:AbsenceDetails/my:EndDate").text) > _
System.Convert.ToString(thisXDocument.DOM.selectSingleNode(
"/dfs:myFields/my:AbsenceDetails/my:StartDate").text) Then
'Calculates the difference between StartDate and EndDate.Dim datStart As Date = thisXDocument.DOM.selectSingleNode("/dfs:myFields/my:AbsenceDetails/my:StartDate").text Dim datEnd As Date = thisXDocument.DOM.selectSingleNode("/dfs:myFields/my:AbsenceDetails/my:EndDate").text
'Add one day to correct the calculation.Dim strDaysOff As String = (DateDiff(Microsoft.VisualBasic.DateInterval.Day, datStart, datEnd) + 1)
'Assigns the result to DaysOffthisXDocument.DOM.selectSingleNode("/dfs:myFields/my:DaysOff").text = strDaysOff
Else
thisXDocument.DOM.selectSingleNode(
"/dfs:myFields/my:DaysOff").text = ""
End If
I know the code is rudamentary, and probably violated some code, or the code could be trimmed down, but it works, and hopefully others will find it usefull.
Also should be noted the +1 was added to the date difference because in my case I needed to know the number of days between the two dates(start and end date). For example For a work week that is monday through friday, using the code above would net a result of 5, because the time span is 5 days, however if you don't put +1 on there then it would be 4 as friday is 4 days after monday. I also would put a rule in infopath to pop a message up if the end date is before the first date, and then zero the box making the user reselect a date later than the start date.