How to compare two dates in c#

{2 Comments}

When there is comparison of two date time data types or just say two dates. Their must be two result we are trying to find first one is to check the date are equal or not, in other case we want to check which date is greater or smaller. In below article there are two function which can be used to understand the method by which we can compare two date in both scenario.

Compare for equal Dates

In this function we are checking the two date are exactly same or not.

 C# |  copy code |? 
01
private void ComapareDate(ref DateTime d1, ref DateTime d2)
02
    {
03
        if (d1 == d2)
04
        {
05
            Response.Write("Date are same");
06
        }
07
        else
08
        {
09
            Response.Write("Date are different");
10
        }
11
    }

Compare which date is greater or smaller

In this function we are checking which one among two provided date are greater or smaller.

 C# |  copy code |? 
01
private void CompareDate_smaller_or_greater(ref DateTime d1, ref DateTime d2)
02
    {
03
        if (d1 > d2)
04
        {
05
            Response.Write(String.Format("Date {0} is smaller then {1}", d2, d1));
06
        }
07
        else
08
        {
09
            Response.Write(String.Format("Date {0} is smaller then {1}", d1, d2));
10
        }
11
    }

2 Comments…

 Share your views
  1. If the format of date is different then how to compare dates.

    • to compare date with different date time format, you have to convert both the date time in same format,
      some thing like this

      string some_date="011/02/2013";

      DateTime data = Convert.ToDateTime(some_date);

      for better performance you can make own function which convert any type of date time to desired format or use system’s default date time convert method.

Leave a Comment Cancel reply

Your email address will not be published.