How to Compare two DateTime input Values

Tripati.patro
Posted by Tripati.patro under C# category on | Points: 40 | Views : 4272
private void CheckValidDateRange()
{
if (DateComparer(DateTime.Now, DateTime.Now.AddDays(1)))
{
MessageBox.Show("End Date is greater or equal to Start Date.");
}
else
{
MessageBox.Show("Start Date is greater than to End Date.");
}
}

/// <summary>
/// Compare two input date to check for valid range.
/// </summary>
/// <param name="startDate">Start Date</param>
/// <param name="endDate">End Date</param>
/// <returns>True if End Date is greater or equal than Start Date.</returns>
private bool DateComparer(DateTime startDate, DateTime endDate)
{
var validDateRange = false;
// If end date is greater or equal to start date.
if (endDate.Date.CompareTo(startDate.Date) >= 0)
{
validDateRange = true;
}

return validDateRange;
}

/// <summary>
/// Compare two input date with time to check for valid range.
/// </summary>
/// <param name="startDate">Start Date</param>
/// <param name="endDate">End Date</param>
/// <returns>True if End Date is greater or equal than Start Date.</returns>
private bool DateTimeComparer(DateTime startDate, DateTime endDate)
{
var validDateRange = false;
if (endDate.CompareTo(startDate) >= 0)
{
validDateRange = true;
}

return validDateRange;
}

Comments or Responses

Posted by: T.saravanan on: 2/22/2011 Level:Silver | Status: [Member] [MVP] | Points: 10
Hi,

Nice Try...

Using compare method achieve the same output.
 if (DateTime.Compare(DateTime.Now, DateTime.Now.AddDays(1)) <= 0)

{
MessageBox.Show("End Date is greater or equal to Start Date.");
}
else
{
MessageBox.Show("Start Date is greater than to End Date.");
}


Cheers :)
Posted by: Tripati.patro on: 2/22/2011 Level:Starter | Status: [Member] | Points: 10
Hi Saravanan,

The reason of making the code into a method is all programmers/developer will be sync to same kind of code. They should not write different way of code to compare two date values.

Login to post response