![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
DateTime.CompareTo() Method in C#
The DateTime.CompareTo() method in C# is used to compare the value of this instance to a specified DateTime value.
Syntax
Following is the syntax −
public int CompareTo (DateTime val);
Above, Val is the date to be compared.
It returns an integer value,
- <0 − If this instance is earlier than Val
- 0 − If this instance is the same as Val
- >0 − If this instance is later than Val
Example
Let us now see an example to implement the DateTime.CompareTo() method −
using System; public class Demo { public static void Main(){ DateTime date1 = new DateTime(2019, 05, 20, 6, 20, 40); DateTime date2 = new DateTime(2019, 05, 20, 6, 20, 40); Console.WriteLine("DateTime 1 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", date1); Console.WriteLine("DateTime 2 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", date2); int res = date1.CompareTo(date2); // returns equal to 0 since date1 is equal to date2 Console.WriteLine(res); } }
Output
This will produce the following output −
DateTime 1 = 20 November 2019, 06:20:40 DateTime 2 = 20 November 2019, 06:20:40 0
Example
Let us now see another example to implement the DateTime.CompareTo() method −
using System; public class Demo { public static void Main(){ DateTime date1 = new DateTime(2019, 08, 20, 6, 20, 40); DateTime date2 = new DateTime(2019, 05, 20, 6, 20, 40); Console.WriteLine("DateTime 1 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", date1); Console.WriteLine("DateTime 2 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", date2); int res = date1.CompareTo(date2); // returns >0 since date1 is later than date2 Console.WriteLine(res); } }
Output
This will produce the following output −
DateTime 1 = 20 August 2019, 06:20:40 DateTime 2 = 20 May 2019, 06:20:40 1
Advertisements