C# | DateTime.CompareTo() Method with Example

DateTime.CompareTo() Method: Here, we are going to learn about the CompareTo() method of DateTime class with example in C#. By IncludeHelp Last updated : August 27, 2023

C# DateTime.CompareTo() Method

DateTime.CompareTo() method is used to compare the given date time with this object.

Syntax

int DateTime.CompareTo(DateTime dt);

Parameter(s)

  • DateTime dt – it represents the DateTime object to be compared.

Return value

The return type of this method is int, it returns an integer value based on the following cases,

  • 0 : If both dates are equal.
  • <0 : If first date by that object we are calling method is earlier then passed date.
  • >0 : If first date by that object we are calling method is later then passed date.

Example to demonstrate example of DateTime.CompareTo() method

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

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.