How to compare a given date from today

I want to compare a given date to today and here is the condition: If provided date is greater than or equal to 6 months earlier from today, return true else return false

Code:

string strDate = tbDate.Text; //2015-03-29
if (DateTime.Now.AddMonths(-6) == DateTime.Parse(strDate)) //if given date is equal to exactly 6 months past from today (change == to > if date has to be less 6 months)
{
    lblResult.Text = "true"; //this doesn't work with the entered date above.
}
else //otherwise give me the date which will be 6 months from a given date.
{
    DateTime dt2 = Convert.ToDateTime(strDate);
    lblResult.Text = "6 Months from given date is: " + dt2.AddMonths(6); //this works fine
}
  • If 6 months or greater than 6 months is what I would like for one condition
  • If less than 6 months is another condition.
Jon Skeet
people
quotationmark

Your first problem is that you're using DateTime.Now instead of DateTime.Today - so subtracting 6 months will give you another DateTime with a particular time of day, which is very unlikely to be exactly the date/time you've parsed. For the rest of this post, I'm assuming that the value you parse is really a date, so you end up with a DateTime with a time-of-day of midnight. (Of course, in my very biased view, it would be better to use a library which supports "date" as a first class concept...)

The next problem is that you are assuming that subtracting 6 months from today and comparing it with a fixed date is equivalent to adding 6 months to the fixed date and comparing it with today. They're not the same operation - calendar arithmetic just doesn't work like that. You should work out which way you want it to work, and be consistent. For example:

DateTime start = DateTime.Parse(tbDate.Text);
DateTime end = start.AddMonths(6);
DateTime today = DateTime.Today;
if (end >= today)
{
    // Today is 6 months or more from the start date
}
else
{
    // ...
}

Or alternatively - and not equivalently:

DateTime target = DateTime.Parse(tbDate.Text);
DateTime today = DateTime.Today;
DateTime sixMonthsAgo = today.AddMonths(-6);
if (sixMonthsAgo >= target)
{
    // Six months ago today was the target date or later
}
else
{
    // ...
}

Note that you should only evaluate DateTime.Today (or DateTime.Now etc) once per set of calculations - otherwise you could find it changes between evaluations.

people

See more on this question at Stackoverflow