c# - 我怎样才能消除这个 FormatException 问题
问题描述
我编写了一个将字符串值转换为 TimeSpan 值的代码。有时它并不总是有 FormatException。它通常运作良好。
为了将字符串减去时间,我对每个字符串值使用了 DateTime.Parse。
TimeSpan timespan = DateTime.Parse(logs_temp[i + 1].time).Subtract(DateTime.Parse(logs_temp[i].time));
这是我的代码的一部分。
public class log
{
[XmlElement("command")]
public int command { get; set; }
[XmlElement("param")]
public int param { get; set;}
[XmlElement("time")]
public string time { get; set; }
}
List<log> logs = logs_temp.ToList();
// logs and logs_temp have same command and param item. However add timespan bewteewn two commands in
// time item
for (int i = 0; i <= logs_temp.Count - 1; i++)
{
logs[i].command = logs_temp[i].command;
logs[i].param = logs_temp[i].param;
//Get a timespan between two sequencial command log
if (i + 1 < logs_temp.Count)
{ // I could find Format exception there
TimeSpan timespan = DateTime.Parse(logs_temp[i + 1].time).Subtract(DateTime.Parse(logs_temp[i].time));
//add second value as string but cannot
logs[i].time = timespan.TotalSeconds.ToString();
}
}
解决方案
DateTime.Parse 尝试使用当前的 PC 文化对其进行解析。如果不能,它将抛出格式异常。所以我猜您提供的时间字符串有时会有所不同。所以设置一个断点来检查。
最好是使用DateTime.TryParseExact或
dateString = "05/01/2009 01:30:42 PM -05:00";
if (DateTime.TryParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS, DateTimeStyles.None, out dateValue))
Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, dateValue.Kind);
else
Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
推荐阅读
- css - CSS Div 随机定位
- actions-on-google - AoG:NodeJS 到 DialogFlow 用户实体
- multithreading - x86 CPU 有多少条内存屏障指令?
- c# - 如何将单独的 C# 文件调用到我的 C# 程序中?
- android - 文件已存在时的 IO 异常 - Gson Android
- php - 将多面额数组处理为数组索引作为数组
- python - 正则表达式捕获“*”,同时排除评论部分
- macos - 是否有任何苹果 API 可以让我们获取 mac 的配置详细信息,例如 RAM 和处理器
- python - Python:将一个数据框中的一列与另一个数据框中的列相除并累积总和
- java - 嵌套异常是 java.io.FileNotFoundException: 类路径资源 [config/simpleJob.xml] 无法打开,因为它不存在