tags:

views:

80

answers:

2

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
thanks, i ended with comparison like yours.
Varyanica
+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
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
thank you. idea of making this method is really cool.
Varyanica
@Luke, very good catch with the leap year. Haven't thought about this.
Darin Dimitrov
Since the year doesn't matter you could just always use a year that is a leap year like `int year = 2008`
Cornelius