Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two DateTimes on Time only ignoring the date?

Tags:

Seems like everyone always ignores the time part, but how would you compare two datetimes ignoring the date? if we just compare them as TIME it seems to still favor the oldest date.

(12/02/2004 9:00) > (12/02/2011 8:24) --this would be true.

The below code works but it feels a bit a bit beating around the bush comparing the hours and minutes separately.

var results = from x in dataContext.GetTable<ScheduleEntity>()                                          where x.LastRunDate < date.Date                && x.reportingTime.Hour <= date.Hour               && x.reportingTime.Minute <= date.Minute               && x.reportingFequency.Substring(position, 1) == scheduled               select x;   

Also, the reason we are doing this is because we couldn't get our SQL TIME to compare to a TIMESPAN this says it would be the same but LINQ is returning a "TIME to bigint conversion error".

like image 779
Andy Avatar asked May 20 '11 09:05

Andy


People also ask

How do you compare only the date and not time?

Fortunately you can use the INT() function in Excel to extract just the date from a datetime value, which allows you to easily compare dates while ignoring the time.

How do you compare only the date?

There are two ways to check if two dates are equal in Java : Date's equals() method - return true if two dates are equal. Date's compareTo() method - return zero if two dates are equal.

How do you compare two date values?

In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.


1 Answers

DateTime has a TimeOfDayProperty, you can use this to compare the times for two dates as follows:

var one = DateTime.Now.AddHours(1); var two = DateTime.Now; var diff = one.TimeOfDay - two.TimeOfDay; 
like image 186
ColinE Avatar answered Oct 11 '22 17:10

ColinE