Comparing Time 2 DateTime C #

What is the best way to compare time of 2 DateTime objects?

for instance

  • DateTime1 = 2012-07-30 01:00
  • DateTime2 = 2012-08-01 02:00

I just need to compare the time NOT date.

thanks

+4
source share
6 answers
 if (DateTime1.TimeOfDay > DateTime2.TimeOfDay) { MessageBox.Show("DateTime1 is later"); } 
+9
source

You can use DateTime.TimeOfDay to get only a fraction of the time for comparison. This is essentially the same as you d - d.Date .

+3
source

Use the TimeOfDay property:

http://msdn.microsoft.com/en-us/library/system.datetime.timeofday.aspx

This gives you the temporary part of the value without the date part.

+3
source

Try something like this:

 TimeSpan ts = d1 - d2; int totalSecondNumber = ts.TotalSeconds; 

TimeSpan is the difference between dates. It gives you properties like TotalSeconds, TotalHours, etc., Or just seconds, hours, etc.

+1
source

Sample code using DateTime.TimeOfDay

 DateTime timeNow = DateTime.Now; DateTime fromTime = new DateTime(2015, 11, 14, 08, 00, 00); DateTime toTime = new DateTime(2015, 11, 14, 14, 30, 00); if (TimeSpan.Compare(timeNow.TimeOfDay, fromTime.TimeOfDay) == 1 && TimeSpan.Compare(timeNow.TimeOfDay, toTime.TimeOfDay) == -1) { } 

In the above code, if the timeNow variable is between 08:00:00 and 14:30:00, then the condition will become true.

 1 represents time1 > time2 0 represents time1 = time2 -1 represents time1 < time2 
+1
source

If you are trying to compare the difference between two points, you should use a Timespan object.

Using Timespan, you can get the difference in seconds, hours and days, etc.

For more information, see the information below:

Timespan

0
source

All Articles