Date Class in C#


To set dates in C#, use DateTime class. The DateTime value is between 12:00:00 midnight, January 1, 0001 to 11:59:59 P.M., December 31, 9999 A.D.

Let’s create a DateTime object.

Example

 Live Demo

using System;
class Test {
   static void Main() {
      DateTime dt = new DateTime(2018, 7, 24);
      Console.WriteLine (dt.ToString());
   }
}

Output

7/24/2018 12:00:00 AM

Let us now get the current date and time.

Example

 Live Demo

using System;
class Test {
   static void Main() {
      Console.WriteLine (DateTime.Now.ToString());
   }
}

Output

9/17/2018 5:49:21 AM

Now using the method Add(), we will add days in a date with the DateTime structure.

Example

 Live Demo

using System;
class Test {
   static void Main() {
      DateTime dt1 = new DateTime(2018, 7, 23, 08, 20, 10);
      Console.WriteLine ("Old Date: "+dt1.ToString());
      DateTime dt2 = dt1.AddDays(7);
      Console.WriteLine ("New Date: "+dt2.ToString());
   }
}

Output

Old Date: 7/23/2018 8:20:10 AM
New Date: 7/30/2018 8:20:10 AM

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 23-Jun-2020

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements