Timespan数据类型C#

jas*_*son 3 c# datetime timespan

我有一个时间跨度值,它是两个日期时间值的差异.它是这样的:

myvalue = {41870.01:44:22.8365404} 
Run Code Online (Sandbox Code Playgroud)

我还有一个代表另一个时间跨度值的字符串,它是这样的:

ttime= "23:55" // which means 23 minutes and 55 seconds
Run Code Online (Sandbox Code Playgroud)

我想检查myvalue是否小于ttime.这是我的尝试:

if(myvalue < Timespan.Parse(ttime))
//do this
else
//do that
Run Code Online (Sandbox Code Playgroud)

我的方法是否足够正确?我还需要做点什么吗?谢谢.

Tim*_*ter 5

我能看到的唯一问题TimeSpan.Parse是限制在24小时内.所以你需要这个解决方法:

string ttime = "48:23:55"; // 48 hours
TimeSpan ts = new TimeSpan(int.Parse(ttime.Split(':')[0]),    // hours
                           int.Parse(ttime.Split(':')[1]),    // minutes
                           int.Parse(ttime.Split(':')[2]));   // seconds
Run Code Online (Sandbox Code Playgroud)

除此之外,以这种方式比较两个时间点是绝对可以的.

如果它可以包含两个或三个部分(有或没有小时),这应该更安全:

string[] tokens = ttime.Split(':');
// support only two or three tokens:
if (tokens.Length < 2 || tokens.Length > 3)
    throw new NotSupportedException("Timespan could not be parsed successfully: " + ttime);
TimeSpan ts;
if(tokens.Length == 3)
    ts = new TimeSpan(int.Parse(tokens[0]), int.Parse(tokens[1]),int.Parse(tokens[2]));
else
    ts = new TimeSpan(0, int.Parse(tokens[0]), int.Parse(tokens[1]));
Run Code Online (Sandbox Code Playgroud)

对于它的价值,这里有一个从头开始编写的方法,TimeSpan通过允许两个或三个标记(hh,mm,ss或mm,ss)解析字符串,并且还支持奇怪的格式,如100:100:100(100小时+ 100分钟+ 100)秒):

public static TimeSpan SaferTimeSpanParse(string input, char delimiter = ':')
{
    if (string.IsNullOrEmpty(input))
        throw new ArgumentNullException("input must not be null or empty", "input");
    string[] tokens = input.Split(delimiter);
    if (tokens.Length < 2 || tokens.Length > 3)
        throw new NotSupportedException("Timespan could not be parsed successfully: " + input);
    int i;
    if (!tokens.All(t => int.TryParse(t, out i) && i >= 0))
        throw new ArgumentException("All token must contain a positive integer", "input");

    int[] all = tokens.Select(t => int.Parse(t)).ToArray();
    int hoursFinal = 0, minutesFinal = 0, secondsFinal = 0;

    int seconds = all.Last();
    secondsFinal = seconds % 60;
    minutesFinal = seconds / 60;

    int minutes = (all.Length == 3 ? all[1] : all[0]) + minutesFinal; // add current minutes which might already be increased through seconds
    minutesFinal = minutes % 60;
    hoursFinal = minutes / 60;

    hoursFinal = all.Length == 3 ? all[0] + hoursFinal : hoursFinal; // add current hours which might already be increased through minutes

    return new TimeSpan(hoursFinal, minutesFinal, secondsFinal);
}
Run Code Online (Sandbox Code Playgroud)

用你的字符串,我的字符串和一个奇怪的字符串测试:

Console.WriteLine(SaferTimeSpanParse("23:55"));
Console.WriteLine(SaferTimeSpanParse("48:23:55"));
Console.WriteLine(SaferTimeSpanParse("100:100:100"));
Run Code Online (Sandbox Code Playgroud)

输出:

00:23:55
2.00:23:55
4.05:41:40
Run Code Online (Sandbox Code Playgroud)