Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare time part of datetime

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"?

like image 358
Friend Avatar asked Apr 24 '12 00:04

Friend


People also ask

How do I compare time in datetime?

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.

How do I compare only time in python?

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.

How can I compare two date fields in SQL?

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.


2 Answers

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. 
like image 196
Justin Pihony Avatar answered Sep 27 '22 18:09

Justin Pihony


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 } 
like image 22
kaveman Avatar answered Sep 27 '22 20:09

kaveman