how to compare month-year with DateParse

If the years are the same, compare the months, if the years are not the same, your year must be smaller than now:

var yourDate = ...;
if((yourDate.Year == DateTime.Now.Year && yourDate.Month < DateTime.Now.Month)
   || yourDate.Year < DateTime.Now.Year)
{
    // yourDate is smaller than todays month.
}

UPDATE:

To check if yourDate is in a certain time range, use this:

var yourDate = ...;
var lowerBoundYear = 2011;
var lowerBoundMonth = 1;
var upperBoundYear = 2012;
var upperBoundMonth = 4;

if(((yourDate.Year == lowerBoundYear && yourDate.Month >= lowerBoundMonth) || 
    yourDate.Year > lowerBoundYear
   ) &&
   ((yourDate.Year == upperBoundYear && yourDate.Month <= upperBoundMonth) ||
    yourDate.Year < lowerBoundYear
   ))
{
    // yourDate is in the time range 01/01/2011 - 30/04/2012
    // if you want yourDate to be in the range 01/02/2011 - 30/04/2012, i.e. 
    // exclusive lower bound, change the >= to >.
    // if you want yourDate to be in the range 01/01/2011 - 31/03/2012, i.e.
    // exclusive upper bound, change the <= to <.
}

var date = DateTime.Parse(o.MyDate);
var year = date.Year;

// We don't even want to know what could happen at 31 Dec 23.59.59 :-)
var currentTime = DateTime.Now;
var currentYear = currentTime.Year;

bool result = year < currentYear || 
                 (year == currentYear && 
                     date.Month <= currentTime.Month)

Second option:

var date = DateTime.Parse(o.MyDate).Date; // We round to the day
date = date.AddDays(-date.Day); // and we remove the day

var currentDate = DateTime.Now.Date;
currentDate = currentDate.AddDays(-currentDate.Day);

bool result = date <= currentDate;

Third option (more "old school" perhaps)

var date = DateTime.Parse(o.MyDate);
var currentTime = DateTime.Now;

// Each year can be subdivided in 12 parts (the months)
bool result = date.Year * 12 + date.Month <= currentTime.Year * 12 + currentTime.Month;

Tags:

C#

Datetime