我在计算两个时间戳之间的差异时遇到问题,当分钟用3位数表示时,例如180:22 = 180分22秒。
那么,你能帮助我如何在时间戳之间找到区别,如:
180:22和122:11
或
232:21和31:34
等
更新:我需要在两次之间获得差异,定义为字符串。出现问题的原因是这些字符串中的分钟数(时间)大于60,并且超出限制。所以我需要知道如何找到差异,如上面的例子(180:22和122:11,以及232:21和31:34)
答案 0 :(得分:1)
使用System.TimeSpan结构:
var seconds=(new TimeSpan(0, 180, 22)-new TimeSpan(0, 122, 11)).TotalSeconds;
var minutes=(new TimeSpan(0, 232, 21)-new TimeSpan(0, 31, 34)).TotalMinutes;
答案 1 :(得分:0)
这是一个可以做这件事的课程:
public class CrazyTime
{
public TimeSpan TimeSpanRepresentation { get; set; }
public CrazyTime(TimeSpan timeSpan)
{
this.TimeSpanRepresentation = timeSpan;
}
public CrazyTime(string crazyTime)
{
// No error checking. Add if so desired
var pieces = crazyTime.Split(new[] { ':' });
var minutes = int.Parse(pieces[0]);
var seconds = int.Parse(pieces[1]);
TimeSpanRepresentation = new TimeSpan(0, minutes, seconds);
}
public static CrazyTime operator-(CrazyTime left, CrazyTime right)
{
var newValue = left.TimeSpanRepresentation - right.TimeSpanRepresentation;
return new CrazyTime(newValue);
}
public override string ToString()
{
// How should negative Values look?
return ((int)Math.Floor(TimeSpanRepresentation.TotalMinutes)).ToString() + ":" + TimeSpanRepresentation.Seconds.ToString();
}
}
以下是它的使用方法:
var a = new CrazyTime("123:22");
var b = new CrazyTime("222:11");
var c = b - a;
Console.WriteLine(c);
答案 2 :(得分:0)
这有效:
string time1 = "180:22";
string time2 = "122:11";
TimeSpan span1 = getTimespan(time1);
TimeSpan span2 = getTimespan(time2);
TimeSpan diff = span1 - span2;
getTimespan只需要正确解析字符串。我决定让Regex这样做,但你可以走任何路线,特别是如果分隔符“:”永远不会改变。
private static TimeSpan getTimespan(string time1)
{
Regex reg = new Regex(@"\d+");
MatchCollection matches = reg.Matches(time1);
if (matches.Count == 2)
{
int minutes = int.Parse(matches[0].Value);
int seconds = int.Parse(matches[1].Value);
return new TimeSpan(0, minutes, seconds);
}
return TimeSpan.Zero;
}