DateTime in C#

When we are dealing with time and date in C#, we often need a data type to store such values easily. So, for this purpose, we have a specific data type called DataTime.

svg viewer

Constructors

There are two ways to initialize the DateTime variable:

DateTime DT = new DateTime();// this will initialze variable with a date(01/01/0001) and time(00:00:00).

DateTime DT = new DateTime(2019,05,09,9,15,0);// this will initialize variable with a specific date(09/05/2019) and time(9:15:00).

Note: The (year, month, day, hour, minute, second) format is followed.

Code

using System;
class DateTimeTesting
{
static void Main()
{
DateTime DT1 = new DateTime();// Default constructor
Console.WriteLine(DT1);
DateTime DT2 = new DateTime(2019,05,09,09,15,00);// Parameterized constructor
Console.WriteLine(DT2);
}
}

Static methods

Here, in the code below, we have given a sample code for two static methods:

  • DaysInMonth(yyyy,mm) : It returns the number of days in the specific month.

  • IsLeapYear(yyyy) : It returns true if the specified year is a leap year and false if otherwise.

using System;
class DateTimeTesting
{
static void Main()
{
int days = DateTime.DaysInMonth(2019,05);
Console.WriteLine(days);
bool isLeap = DateTime.IsLeapYear(2019);
Console.WriteLine(isLeap);
}
}

Click here for the complete documentation.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved