Timespan数据类型C#

时间:2014-08-21 08:53:15

标签: c# datetime timespan

我有两个Datetime值的差异的时间跨度值。就像这样:

myvalue = {41870.01:44:22.8365404} 

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

ttime= "23:55" // which means 23 minutes and 55 seconds

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

if(myvalue < Timespan.Parse(ttime))
//do this
else
//do that

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

1 个答案:

答案 0 :(得分: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

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

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

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

对于它的价值,这是一个从头开始编写的方法,通过允许两个或三个标记(hh,mm,ss或mm,ss)将字符串解析为TimeSpan,并且还支持奇怪的格式,如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);
}

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

Console.WriteLine(SaferTimeSpanParse("23:55"));
Console.WriteLine(SaferTimeSpanParse("48:23:55"));
Console.WriteLine(SaferTimeSpanParse("100:100:100"));

输出:

00:23:55
2.00:23:55
4.05:41:40