C# DateTime.CompareTo() Method with Example

DateTime.CompareTo() Method: Here, we will find out about the CompareTo() strategy for DateTime class with example in C#.

DateTime.CompareTo() Method

DateTime.CompareTo() technique is utilized to contrast the given date time and this article.

Syntax:

int DateTime.CompareTo(DateTime dt);

Parameter(s):

DateTime dt – it speaks to the DateTime item to be thought about.

Return value:

  • The arrival sort of this technique is int, it restores an integer value dependent on the accompanying cases,
  • 0: If the two dates are equivalent.
  • <0: If the first date by that item we are calling strategy is prior then passed date.

Example to show example of DateTime.CompareTo() technique

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int res=0;

            //Create object of datetime class
            DateTime dt1 = new DateTime(2019,1,1,5,0,15);
            DateTime dt2 = new DateTime(2019,1,1,5,0,15);
            DateTime dt3 = new DateTime(2019,1,2,5,0,15);
            
            
            //Compare dt1 and dt2 and return result.
            res = dt1.CompareTo(dt2);

            if(res==0)
                Console.WriteLine("dt1 and dt2 are equal");
            else if(res<0)
                Console.WriteLine("dt1 is earlier then dt2");
            else
                Console.WriteLine("dt1 is later then dt2");


            //Compare dt1 and dt3 and return result.
            res = dt1.CompareTo(dt3);
            if (res == 0)
                Console.WriteLine("dt1 and dt3 are equal");
            else if (res < 0)
                Console.WriteLine("dt1 is earlier then dt3");
            else
                Console.WriteLine("dt1 is later then dt3");

            Console.WriteLine();  
        }
    }
}

Output

dt1 and dt2 are equal
dt1 is earlier then dt3

Leave a Comment

error: Alert: Content is protected!!