Working with DateTime in C#



The DateTime class in C# is used to represent date and time in C#.

The following are some of the properties of DateTime in C# −

Sr.No Property & Description
1 Date
Gets the Date component
2 Day
Gets the day of the month
3 Hour
Gets the hour of the month
4 Minute
Gets the minute of the date
5 Month
Gets the month of the date

Let us see an example to compare date in C#.

To compare dates in C#, you need to first set two dates to be compared using the DateTime object. We will use the DateTime class in C# −

Date 1

DateTime date1 = new DateTime(2018, 07, 20);
Console.WriteLine("Date 1 : {0}", date1);

Date 2

DateTime date2 = new DateTime(2018, 07, 25);
Console.WriteLine("Date 2 : {0}", date2);

Now let us compare both the dates in C#. The following is an example to compare dates in C# −

Example

 Live Demo

using System;
namespace Program {
   class Demo {
      static int Main() {
         DateTime date1 = new DateTime(2018, 07, 20);
         Console.WriteLine("Date 1 : {0}", date1);

         DateTime date2 = new DateTime(2018, 07, 25);
         Console.WriteLine("Date 2 : {0}", date2);
         if (date1 < date2)
         Console.WriteLine("{0} comes before {1}", date1, date2);
         Console.Read();
         return 0;

      }
   }
}

Output

Date 1 : 7/20/2018 12:00:00 AM
Date 2 : 7/25/2018 12:00:00 AM
7/20/2018 12:00:00 AM comes before 7/25/2018 12:00:00 AM
Updated on: 2020-06-20T11:16:17+05:30

750 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements