Date Comparison in C#

Sometime you may need to compare dates which are stored in variables in string format.

The following CompareDates() function written in C# will help you to accept two dates StartDate and EndDate in string format, convert them into date format, compares them and returns -1 if StartDate less than EndDate, 0 if Equal and 1 if StartDate greater than EndDate.

I assume that the user will enter the date in dd/MM/yyyy format. But if we use Convert.ToDateTime() or DateTime.Parse() methods, these functions will use the applications cultural settings specified in the configuration file or local settings of the computer.

Therefore we need to use cultural info to format the date before the convertion.

I have used English (United Kingdom) cultural inforamtion to convert data into dd/MM/yyyy format using CultureInfo and DateTimeFormatInfo classes. These classes are available in the System.Globalization namespace.

using System;
using System.Globalization;

public class Helper
/// Returns -1 if StartDate less than EndDate,
/// 0 if Equal.
/// 1 if StartDate greater than EndDate
public static int CompareDates(string strStartDate, string strEndDate)
// Creates and initializes the CultureInfo which uses the international sort.
//I have used English (United Kingdom) cultural inforamtion to convert data into dd/MM/yyyy format
CultureInfo cultInfo = new CultureInfo("en-GB", true);
DateTimeFormatInfo formatInfo = cultInfo.DateTimeFormat;

formatInfo.ShortDatePattern = "dd/MM/yy";
formatInfo.ShortDatePattern = "dd/MM/yyyy";
formatInfo.LongDatePattern = "dd MMMM yyyy";
formatInfo.FullDateTimePattern = "dd MMMM yyyy HH:mm:ss";

DateTime startDate = new DateTime();
DateTime endDate = new DateTime();

//Convert strStartDate which is passed as string argument into date
if (!String.IsNullOrEmpty(strStartDate))
startDate = System.Convert.ToDateTime(strStartDate, formatInfo);

//Convert strEndDate which is passed as string argument into date
if (!String.IsNullOrEmpty(strEndDate))
endDate = System.Convert.ToDateTime(strEndDate, formatInfo);

return DateTime.Compare(startDate, endDate);

catch (Exception ex)
throw ex;

To test this function, write the following code in the button _click event of an button.

protected void Button1_Click(object sender, EventArgs e)
string stDate = "20/04/2009";
string enDate = "11/06/2009";
int result = Helper.CompareDates(stDate, enDate);

if (result < 0)
Response.Write(stDate + " is less than " + enDate);
else if (result == 0)
Response.Write(stDate + " is equal to " + enDate);
Response.Write(stDate + " is greater than " + enDate);



No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: