[英]C# date time to listbox
我有一台帶有.txt文件的服務器。 該程序將頁面保存到文本文件,然后使用count每行對其進行處理。 然后,我需要將其添加到日期時間,然后將其添加到列表中。
到目前為止,除了最后一部分的日期時間和列表之外,它還算不錯。 我總是收到格式異常。 我嘗試了一些嘗試解析和沒有運氣的解析方法。
時間在這樣的列表中:
06:06 AM
06:07
12:12
12:50
每行一個
消息框一次顯示每個結果,沒有錯誤且信息正確。
while ((line = file.ReadLine()) != null)
{
// MessageBox.Show(line);
List<DateTime> Busarrivetime = new List<DateTime>();
// DateTime tryme = DateTime.Parse(line, CultureInfo.InvariantCulture);
// MessageBox.Show(tryme.ToString());
DateTime date;
Busarrivetime.Add(date = DateTime.ParseExact(line,"hh:mm tt", System.Globalization.CultureInfo.InvariantCulture)); // ERRORS ON THIS LINE
count++;
}
file.Close();
Console.ReadLine();
確切錯誤:
mscorlib.dll中發生了'System.FormatException'類型的未處理異常
您的時間格式不一致。 例如,06:06 06:06 AM
有am / pm指示符,而12:12
則沒有。
因此,請考慮使用多種可能的格式。
DateTime.ParseExact(item, new[] { "hh:mm tt", "HH:mm" }, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None);
這應該工作
它是一個簡單的解決方案
我使用此DateTime.ParseExact("06:06 AM ", "hh:mm tt", System.Globalization.CultureInfo.InvariantCulture);
並得到與您相同的例外。
但是用這個測試
DateTime.ParseExact("06:06 AM", "hh:mm tt", System.Globalization.CultureInfo.InvariantCulture);
沒有得到。 文件正在獲取尾隨或前導空格。
使用.Trim()函數:)刪除它們,然后進行測試
DateTime.ParseExact(("06:06 AM ").Trim(), "hh:mm tt", System.Globalization.CultureInfo.InvariantCulture);
文件末尾是否可能還有多余的空白行?
// add this just inside your while loop
if (String.IsNullOrWhiteSpace(line))
continue;
另外,您需要在while循環之前聲明列表,否則您將只為每一行獲取一個新列表,而不是將其添加到一個大列表中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.