Reputation: 467
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
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
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:
Upvotes: 0
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
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
Reputation: 869
if (DateTime1.TimeOfDay > DateTime2.TimeOfDay)
{
MessageBox.Show("DateTime1 is later");
}
Upvotes: 9
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