Let's say we have
DateTime t1 = DateTime.Parse("2012/12/12 15:00:00.000");
and
DateTime t2 = DateTime.Parse("2012/12/12 15:03:00.000");
How to compare it in C# and say which time is "is later than"?
kaveman
The <
, <=
, >
, >=
, ==
operators all work directly on DateTime
and TimeSpan
objects. So something like this works:
DateTime t1 = DateTime.Parse("2012/12/12 15:00:00.000");
DateTime t2 = DateTime.Parse("2012/12/12 15:03:00.000");
if(t1.TimeOfDay > t2.TimeOfDay) {
//something
}
else {
//something else
}
Use the DateTime.Compare
method:
DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
DateTime date2 = new DateTime(2009, 8, 1, 12, 0, 0);
int result = DateTime.Compare(date1, date2);
string relationship;
if (result < 0)
relationship = "is earlier than";
else if (result == 0)
relationship = "is the same time as";
else
relationship = "is later than";
Console.WriteLine("{0} {1} {2}", date1, relationship, date2);
Edit: If you just want to compare the times, and ignore the date, you can use the TimeOfDay
as others have suggested. If you need something less fine grained, you can also use the Hour
and Minute
properties.
来源:https://stackoverflow.com/questions/10290187/how-to-compare-time-part-of-datetime