我想出瞭如何解析輸入字符串到日期時間對象。如何解析一個字符串輸入到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