簡體   English   中英

如何解析輸入到DateTime的字符串?

[英]How to parse a string input to a DateTime?

我想出了如何將輸入字符串解析為日期時間對象。

但是,如果我輸入了字符串並運行了啟動計時器然后停止的方法,那么在沒有格式異常的情況下我無法重新編輯字符串輸入。

在測試中,我輸入: "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);

有沒有辦法在代碼中處理這種類型的輸入異常,或者可能是我在解析字符串時缺少的額外步驟?

{這是評論,不是答案,但我需要正確設置其格式。}

必須有其他信息導致您沒有提供該問題。 這對我有用:

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);

但是,由於僅處理時間數據,因此最好使用TimeSpan

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);

請注意,使用TimeSpan.Parse ,冒號和空格需要轉義。

嘗試轉換類:

myDateAsString="3/29/2014";
try
{
Convert.ToDate(myDateAsString)
}
catch(Format exception)
{
//do something
}

我同意這是另一種方法,但是我認為它更容易,希望對您有所幫助:)

如果您知道可能會出問題,建議您使用TryParseExact方法。

我還建議在處理時間間隔時使用TimeSpan而不是DateTime。 無論如何,DateTime也存在該方法。

TimeSpan ts;
if (TimeSpan.TryParseExact(wrkString.Replace(": ", ":").Replace(" :", ":"), "HH:mm:ss:fff", CultureInfo.InvariantCulture, out ts))
{
   //ts formatted successfully
}
else
{
    //failure
}

您還可以使用DateTime.TryParse進行轉換。

DateTime dateValue;
string[] dateStrings = "1/1/2014";
if (DateTime.TryParse(dateString, out dateValue)) 
{
//code
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM