我想出了如何解析输入字符串到日期时间对象。如何解析一个字符串输入到DateTime?
但是,如果我输入字符串并运行启动计时器的方法然后停止它,我不能重新编辑字符串输入没有得到格式异常。
在测试中,我输入:"00 : 00 : 10 : 000"
,然后开始我的定时器和秒表,但是当我打电话停止双方并尝试输入一个新值的字符串,如"00 : 00 : 22 : 000"
它使我有以下异常:
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.
这是怎样的字符串被解析到一个日期时间:
//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);
有没有办法在代码或可能是一个额外的步骤我错过在解析字符串处理这种类型的输入的异常?
如果您正在使用时间间隔,则可以使用TimeSpan而不是DateTime。 – Luizgrs 2014-10-09 18:01:22
您的“DateTime”字符串不包含日期信息。正如Luizgrs建议使用[TimeSpan](http://msdn.microsoft.com/en-us/library/system.timespan(v = vs.110).aspx_)。 – Jasen 2014-10-09 18:03:45