2

我需要以大于 24 小时的时间跨度格式从字符串中获取总秒数。下面是我使用的代码片段

static void Main(string[] args)
    {
        string s = "24:55:00.00";
        double d = (int)TimeSpan.Parse(s).TotalSeconds;
        Console.WriteLine(d);            
    }

当我跑到上面得到 Exception OverflowException 未处理时。当我使用少于 24 小时的字符串时,比如 23:55:05.09 。代码工作正常。这是 C# 的真正限制还是我遗漏了什么

谢谢

4

3 回答 3

6

小时内使用时间不能超过 23 小时

OverflowException s 表示小于 TimeSpan.MinValue 或大于 TimeSpan.MaxValue 的数字。-或 -天、小时、分钟或秒组件中的至少一个超出其有效范围。

在 MSDN 上看到这里

最大小时数为 23,分钟数为 60 等。

将您的字符串更改为:

1:0:55:00.00

它将等于 24h55m

于 2013-10-25T06:58:32.597 回答
2

To be able to parse a string representation of a time span of 24 hours and 55 minutes you have to use this string:

1.0:55:00.00

If you are unsure about the string representation used by TimeSpan you can perform the reverse conversion:

(TimeSpan.FromDays(1) + TimeSpan.FromMinutes(55)).ToString()

This will return the string:

1.0:55:00
于 2013-10-25T06:59:12.677 回答
1

You cannot use a time span with more than 23 hours, 59 minutes, 59 seconds, 99 miliseconds you could use this code if you want to enter time spans with over 24 hours:

string s = "24:55:00.00";
string hoursS = s.Split(':')[0];
double hours = int.Parse(hoursS);

double totalSeconds = hours*3600;

s = s.Substring(hoursS.Length);
s = "00" + s;
double d = (int)TimeSpan.Parse(s).TotalSeconds;

totalSeconds += d;
Console.WriteLine(totalSeconds);

If you would like to use over 60 minutes, seconds, miliseconds in your string as well you can improve easily add it basing on the code I provided.

于 2013-10-25T07:08:05.597 回答