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"?
When you have two datetime objects, the date and time one of them represent could be earlier or latest than that of other, or equal. To compare datetime objects, you can use comparison operators like greater than, less than or equal to. Like any other comparison operation, a boolean value is returned.
Just call the . time() method of the datetime objects to get their hours, minutes, seconds and microseconds. Show activity on this post. Compare their times using datetime.
This can be easily done using equals to(=), less than(<), and greater than(>) operators. In SQL, the date value has DATE datatype which accepts date in 'yyyy-mm-dd' format. To compare two dates, we will declare two dates and compare them using the IF-ELSE statement.
You can use the TimeOfDay property and use the Compare against it.
TimeSpan.Compare(t1.TimeOfDay, t2.TimeOfDay)
Per the documentation:
-1 if t1 is shorter than t2. 0 if t1 is equal to t2. 1 if t1 is longer than t2.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With