嗨,我必须比较HH:MM(小时和分钟).我怎么能这样做?
var t1 = DateTime.Now.ToString("HH:mm");
var t2 = "20:03";
var res =result(t1, t2);
public int result(string t1, string t2)
{
int i = -1;
int hr1 = Convert.ToInt32(t1.Split(':')[0]);
int hr2 = Convert.ToInt32(t2.Split(':')[0]);
int min1 = Convert.ToInt32(t1.Split(':')[1]);
int min2 = Convert.ToInt32(t2.Split(':')[1]);
if (hr2 >= hr1)
{
if (min2 >= min1)
{
i = 1;
}
}
return i;
}
Run Code Online (Sandbox Code Playgroud)
但它不正确..它没有照顾所有条件..如何使它完美.或者是否有任何内置函数只使用thsi输入执行此操作(我检查但没有答案).
提前致谢
如果您可以假设这两个字符串已经是正确的格式,只需使用:
return t1.CompareTo(t2);
Run Code Online (Sandbox Code Playgroud)
毕竟,由于使用的格式,它们按字典顺序排序 - 无需解析:)
所有引用TimeSpan...当然如果您使用Noda Time,您可以使用:
private static readonly LocalTimePattern TimePattern =
LocalTimePattern.CreateWithInvariantInfo("HH:mm");
...
public int CompareTimes(string t1, string t2)
{
// These will throw if the values are invalid. Use TryGetValue
// or the Success property to check first...
LocalTime time1 = TimePattern.Parse(t1).Value;
LocalTime time2 = TimePattern.Parse(t2).Value;
return time1.CompareTo(time2);
}
Run Code Online (Sandbox Code Playgroud)
(TimeSpan当然,你可以随意使用......但是LocalTime代表你所获得的实际数据类型:一天的时间,而不是一段时间的流逝;)
| 归档时间: |
|
| 查看次数: |
2055 次 |
| 最近记录: |