I have to compare three dates in linq query (datetime a < datetime b < datetime c), but just properties month and day. How can i do it?
+3
A:
Is this what you are looking for:
(a.Month < b.Month || (a.Month == b.Month && a.Day < b.Day)) && (b.Month < c.Month || (b.Month == c.Month && b.Day < c.Day))
Cornelius
2010-03-11 12:21:22
thanks, i ended with comparison like yours.
Varyanica
2010-03-11 12:42:34
+3
A:
You may create a new datetime with the current year:
var year = DateTime.Now.Year;
var dateATemp = new DateTime(year, dateA.Month, dateA.Day);
var dateBTemp = new DateTime(year, dateB.Month, dateB.Day);
var dateCTemp = new DateTime(year, dateC.Month, dateC.Day);
Now compare dateATemp < dateBTemp < dateCTemp
You could write an extension method from DateTime that will return you a new DateTime instance with the current year:
public static DateTime ToDateTimeWithCurrentYear(this DateTime value)
{
return new DateTime(DateTime.Now.Year, value.Month, value.Day);
}
and use it like this:
dateA.ToDateTimeWithCurrentYear() < dateB.ToDateTimeWithCurrentYear() < dateC.ToDateTimeWithCurrentYear()
Darin Dimitrov
2010-03-11 12:22:41
Watch out for leap years! If the user's date is Feb 29th but `DateTime.Now` isn't in a leap year then you'll hit an exception. Other than that, this is similar to what I'd have suggested so +1.
LukeH
2010-03-11 12:39:40
@Luke, very good catch with the leap year. Haven't thought about this.
Darin Dimitrov
2010-03-11 13:15:42
Since the year doesn't matter you could just always use a year that is a leap year like `int year = 2008`
Cornelius
2010-03-12 08:18:56