[英]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.