Home » C#

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#.
Submitted by IncludeHelp, on October 22, 2019

DateTime.CompareTo() Method

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


    int DateTime.CompareTo(DateTime dt);


  • 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);

                Console.WriteLine("dt1 and dt2 are equal");
            else if(res<0)
                Console.WriteLine("dt1 is earlier then dt2");
                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");
                Console.WriteLine("dt1 is later then dt3");



dt1 and dt2 are equal
dt1 is earlier then dt3

Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.