Working with Date and Time in C#

Mustafa Ozdemir
baakademi
Published in
2 min readAug 30, 2020

This article is about Date and Time in C#. DateTime and TimeSpan structures are used for date and time operations in C # language. These two structures are included in the “System” namespace.

Creating the DateTime Structure

There are multiple methods to create DateTime. Most used ones are listed below.

DateTime newDate = new DateTime(year, month, day);
DateTime newDate = new DateTime(year, month, day, hour, munite, second);

DateTime Static Fields and Methods

DateTime struct includes static fields, properties, and methods. Static methods come in handy for quick time operations. Some static methods are listed below with their explanation.

DateTime currentDateTime = DateTime.Now;  //returns current date and time
DateTime todaysDate = DateTime.Today; // returns today's date
DateTime currentDateTimeUTC = DateTime.UtcNow;// returns current UTC date and time

DateTime maxDateTimeValue = DateTime.MaxValue; // returns max value of DateTime
DateTime minDateTimeValue = DateTime.MinValue; // returns min value of DateTime

C# provides large-scaled Time methods for .NET. It makes complex time operations simpler.

DateTime date = new DateTime(1991, 7, 10, 7, 10, 25);Console.WriteLine(“Day:{0}”, date.Day);// returns the dayConsole.WriteLine(“Month:{0}”, date.Month);//returns the month of the time element.Console.WriteLine(“Year:{0}”, date.Year);//returns the year.Console.WriteLine(“Hour:{0}”, date.Hour);//returns the hour.Console.WriteLine(“Minute:{0}”, date.Minute);//returns the minute.Console.WriteLine(“Second:{0}”, date.Second);//returns the second.Console.WriteLine(“Millisecond:{0}”, date.Millisecond);//returns the second.Console.WriteLine(“Day of Week:{0}”, date.DayOfWeek);//returns the name of the day in a week.Console.WriteLine(“Day of Year: {0}”, date.DayOfYear);// returns the day of a year.Console.WriteLine(“Time of Day:{0}”, date.TimeOfDay);// returns the time element in DateTime.

Finding the number of days between two dates

Timespan struct is used to represent time intervals in C#. TimeSpan can be used to add, subtract or compare two-time span values.

Calculating the difference between two dates, the method returns in TimeSpan type. For this, a TimeSpan type variable needs to be declared while obtaining the difference. In below example, It is shown usage of DateTime and TimeSpan to calculate age.

// Calculate age with TimeSpan struct
int GetAge(DateTime birthdate)
{
DateTime currenttime = DateTime.Now;
TimeSpan ts = currenttime — birthdate;
int calculateage = (ts.Days) / 365;
return calculateage;
}

This article was a sum up of DateTime and TimeSpan class in C#. Basic and most significant topics are covered. Hope you enjoy it.

--

--