32

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

1 Answer 1

64

DateTime has a TimeOfDay property, 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;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.