【发布时间】:2014-10-09 17:57:31
【问题描述】:
我已经弄清楚如何将输入字符串解析为日期时间对象。
但是如果我输入字符串并运行启动计时器的方法然后停止它,我无法重新编辑字符串输入而不会出现格式异常。
在测试中我输入:"00 : 00 : 10 : 000",然后启动我的计时器和秒表,但是当我对两者都调用 stop 并尝试为字符串输入一个新值时,例如"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。
-
您的“DateTime”字符串不包含日期信息。正如 Luizgrs 建议的那样,使用 TimeSpan。
标签: c# string datetime stopwatch formatexception