Maxime
Maxime

Reputation: 467

Comparison between time of 2 DateTime c#

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

For example

I just need to compare the time NOT the date.

Thanks

Upvotes: 4

Views: 193

Answers (6)

Pranesh Janarthanan
Pranesh Janarthanan

Reputation: 1194

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 variable timeNow is between 08:00:00 to 14:30:00 then the condition become true.

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

Upvotes: 1

Gaz Winter
Gaz Winter

Reputation: 2989

If you are trying to compare the difference between the two times you should use the Timespan object.

By using a Timespan you are able to get the difference in seconds, hours and days etc.

Check out the following for more information:

Timespan

Upvotes: 0

phoog
phoog

Reputation: 43036

Use the TimeOfDay property:

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

This gives you the time portion of the value without the date portion.

Upvotes: 3

Joey
Joey

Reputation: 354356

You can use DateTime.TimeOfDay to get just the time part to compare. This is essentially the same as if you did d - d.Date.

Upvotes: 3

CSharpDev
CSharpDev

Reputation: 869

if (DateTime1.TimeOfDay > DateTime2.TimeOfDay)
{
    MessageBox.Show("DateTime1 is later");
}

Upvotes: 9

Tony Kh
Tony Kh

Reputation: 1572

Try something like this:

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

TimeSpan is a difference between to dates. It gives you properties like TotalSeconds, TotalHours and so on or just Seconds, Hours, etc

Upvotes: 1

Related Questions