首页 > 解决方案 > 我怎样才能消除这个 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();
    }
}

标签: c#exception

解决方案


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

推荐阅读