How to programmatically do math operations on two fields of type "Time" in Infopath

644 views Asked by At

I have an issue here that hopefully someone can help me out with.

I have created a time card in infopath and would like to have some calculations perform automatically based on values entered by the user. I had originally done this using a combination of rules, unfortunately I got hit with the "infinite loop" warning once the form was in SharePoint, because it performed more than 16 calculations.

So, I decided to switch to c# to make the calculations a lot easier. However, I am not sure how to actually perform the parsing of the time field into a datetime variable, and googling hasn't been much of a friend in this case, as everyone is offering "no code" solutions.

I was able to find this example, which is close to what I want, except they seem to be going for a date field using DateTime.ParseExact().

I made my form convert the value of a time field into a string just to test the value to see what I get. I used 8:01 AM for example and got the following as the string value: "08:01:00-08:00".

I get that the first part of the value is representing 8:01 and no milliseconds, I'm not even sure what the part after the dash is supposed to signify though?

Does anyone know how I might convert that to a datetime variable in C#, so that I might be able to do some calculations on it? Any help here would be HUGELY appreciated. Thank you in advance for your time.

1

There are 1 answers

4
Deepak Bhatia On

As you stated that the strings are in Time format, rather trying to format them to DateTime we can use TimeSpan,

static void Main(string[] args)
{
    string[] dateValues = { "08:01 AM", "08:01 PM" };
    string[] pattern = new string[] { @"hh\:mm\ \A\M", @"hh\:mm\ \P\M" };

    DateTime parsedDate;
    TimeSpan interval = new TimeSpan();
    foreach (string dateValue in dateValues)
    {
        if (TimeSpan.TryParseExact(dateValue, pattern, null, out interval))
            Console.WriteLine("{0} --> {1}", dateValue, interval.ToString("c"));
        else
            Console.WriteLine("Unable to parse '{0}'", dateValue);
    }
}

May be this can help you to approach your problem a little differently.

Since you are talking about calculations, I believe you would need time in 24 hours format so you can tweak the code and check if the TimeSpan is parsed by PM format and then you can perform your calculation based on that.

You can refer MSDN documentation for more and detailed information.