Search code examples
c#stringdatetimestopwatchformatexception

How to parse a string input to a DateTime?


I've figured out how to parse the input string to a date time object.

But if I input the string and run the method that starts the timer then stop it, I can't re edit the string input without getting a format exception.

In testing I input: "00 : 00 : 10 : 000" and then start my timer and stopwatch but when I call stop to both and try to input a new value for the string, eg "00 : 00 : 22 : 000" it gives me the following exception:

An exception of type 'System.FormatException' occurred in mscorlib.ni.dll but was not handled in user code

Additional information: String was not recognized as a valid DateTime.

This is how the strings are being parsed to a date time:

            //Assign text box string value to a date time variable.
            DateTime workDt = DateTime.ParseExact(wrkString.Replace(": ", ":").Replace(" :", ":"), "HH:mm:ss:fff", CultureInfo.InvariantCulture);
            DateTime restDt = DateTime.ParseExact(rstString.Replace(": ", ":").Replace(" :", ":"), "HH:mm:ss:fff", CultureInfo.InvariantCulture);

Is there a way to handling this type of input exception in the code or possibly an extra step I'm missing in parsing the string?


Solution

  • {This is a comment, not an answer, but I needed to format it properly.}

    There must be some other information causing the problem that you're not providing. This works for me:

    string s= "00 : 00 : 10 : 000";
    DateTime workDt = DateTime.ParseExact(s, "HH : mm : ss : fff", CultureInfo.InvariantCulture);
    s= "00 : 00 : 22 : 000";
    DateTime restDt = DateTime.ParseExact(s, "HH : mm : ss : fff", CultureInfo.InvariantCulture);
    

    However since you're only dealing with time data you would be better off using TimeSpan instead:

    string s= "00 : 00 : 10 : 000";
    TimeSpan workTm = TimeSpan.ParseExact(s, @"hh\ \:\ mm\ \:\ ss\ \:\ fff", CultureInfo.InvariantCulture);
    s= "00 : 00 : 22 : 000";
    TimeSpan restTm = TimeSpan.ParseExact(s, @"hh\ \:\ mm\ \:\ ss\ \:\ fff", CultureInfo.InvariantCulture);
    

    Notice that when using TimeSpan.Parse the colons and spaces need to be escaped out.