C#: Working With Dates

In a previous article, we talked about working with strings and string builder classes. In this article, I am going to explain another equally important C# concept, working with dates. Microsoft .NET framework contains DateTime structure which can be used to create date and time data in various formats. The DateTime structure can hold any value between 12:00:00 Midnight from January, 01 0001 to 11:59:59 PM, December 31, 9999.

This article briefly explains following concepts related dates in C#.

  • Creating DateTime Objects.
  • DateTime Properties
  • Adding and Subtracting date and time from DateTime
  • DateTime object Comparison
  • Finding Number of Days in a Month

Creating a DateTime Object

There are multiple ways to create a DateTime object in C#. A DateTime object can have a Date, Time, Milliseconds, Culture, localization, and kind. Take a look at the following example to see what different ways are to create DateTime object in C#.

// Date object with time and date
DateTime TimeAndDate = new DateTime(1989, 11, 2, 11, 15, 16);

// Date object using date only
DateTime DateOnly = new DateTime(1989, 11, 2);

// Localized date object
DateTime Localized =  new DateTime(1989, 11, 2, 19, 30, 45, DateTimeKind.Local);

Take a look at the above code. In the first line, a DateTime constructor with six parameters has been used to create DateTime object. Here the first parameter is the year, the second parameter is the month, the third is the date, followed by time in hours, minutes and seconds.

You can create a DateTime object with the date only by passing values for year, month and day. .NET will assume that the time for the date is 12:00:00 AM. If you print the DateTime object created via date only, you can see that it will have 12:00:00 AM as time. Finally, you can also create localized date and time. This is done by passing an additional parameter i.e. DateTimeKind.Local. The output of the above example will look like this:

11/2/1989 11:15:16 AM
11/2/1989 12:00:00 AM
11/2/1989 7:30:45 PM

DateTime Properties

Once, you have created a DateTime object you can use its properties to fetch useful information. For instance, you can get Day, Month, Year, Hour, Minute and Second from the DateTime object. You can also retrieve day of the week, the day of year and time of day from the DateTime object. Take a look at the following example to see these properties in action.

DateTime MyDate = new DateTime(1989, 11, 2, 15, 30, 15);

Console.WriteLine("Day: " + MyDate.Day);
Console.WriteLine("Month: " + MyDate.Month);
Console.WriteLine("Year: " + MyDate.Year);
Console.WriteLine("Hour: " + MyDate.Hour);
Console.WriteLine("Minute: " + MyDate.Minute);
Console.WriteLine("Second: " + MyDate.Second);
Console.WriteLine("Day of Week: " + MyDate.DayOfWeek);
Console.WriteLine("Day of Year: " + MyDate.DayOfYear);
Console.WriteLine("Time of Day: " + MyDate.TimeOfDay);

The output of the above code should look like this:

Day: 2
Month: 11
Year: 1989
Hour: 15
Minute: 30
Second: 15
Day of Week: Thursday
Day of Year: 306
Time of Day: 15:30:15

The output gives us some information about the date 11/2/1989 03:30:15 PM. In this date, the day of the month is 2, the month of the year is 11th and the year is 1989. Similarly, the hour is 15 (3 pm), the minute is 30, and the second is 15. The day of the week on this date is Thursday. I would suggest you to practice with these properties because they will come very handy in your everyday C# programming endeavors.

Adding and Subtracting Date and Time from Datetime

You can easily add and subtract date and time to and from any DateTime object respectively. To do so, you to create a TimeSpan object and assign it days, hours, minutes, seconds and milliseconds. Next, you can add or subtract this TimeSpan object from DateTime object via Add and Subtract methods. Take a look at the following example.

DateTime date1 = DateTime.Now;

TimeSpan days15 = new TimeSpan(15, 0, 0, 0);
date1 = date1.Add(days15);

date1 = DateTime.Now.Subtract(days15);

In the above code,  a DateTime object date1 is initialized with the current system date and time. To retrieve current date and time of the system use “Now” property. Next, a TimeSpan object is created with a value of 15 days. The first parameter in the TimeSpan constructor is the number of days. Next, this TimeSpan object is added to the date1 object and the result value is printed. Similarly, the subtract method is used to subtract 15 days from the current date and time. The output of the above code looks like this:

9/4/2016 12:57:43 PM
9/19/2016 12:57:43 PM
8/20/2016 12:57:43 PM

You can directly add Months, Days, Hours, Minutes, Seconds and Milliseconds to any DateTime object via AddMonths, AddDays, AddHours, AddMinutes, AddSeconds and AddMilliseconds methods, respectively. Take a look at the following example to see these functions in action.

DateTime date1 = new DateTime(1989, 11, 2, 14, 30, 10);

In above example,  5 years, 5 days, 5 hours, 5 minutes, 5 seconds and  5000 milliseconds are added to some random date. The new date is displayed on the console. In the output you shall see an increment of 5 in the year, day, month, minute, second and millisecond on each line. The output of the above example will look like this:

DateTime Comparison

Date comparison is a crucial task in web application development. For instance, you have designed a form where a user enters his date of birth as well as the date of graduation. You must implement the check which ensures that date of birth should be some date earlier than the date of graduation. In such cases, date comparison comes handy.

In C#, there are a couple of ways to compare two dates. Static “Compare” method of DateTime structure takes two dates and returns an integer. If the integer is less than zero, the first date comes before the second date. If the integer is zero, both dates are same. Similarly, if the integer is greater than zero then second date comes before the first one.

Another way of date comparison is to call CompareTo method on DateTime object. It takes a date to compare with the object. The following example demonstrates both methods.

DateTime date1 = new DateTime(1989, 11, 2);
DateTime date2 = new DateTime(1978, 4, 15);
int dateResult = DateTime.Compare(date1, date2);

if (dateResult < 0)
	Console.WriteLine("First date comes earlier.");
else if (dateResult == 0)
	Console.WriteLine("Dates are equal.");
	Console.WriteLine("Second date comes earlier.");

// Second Method
int dateResult2 = date1.CompareTo(date2);
if (dateResult2 < 0)
	Console.WriteLine("First date comes earlier.");
else if (dateResult2 == 0)
	Console.WriteLine("Dates are equal.");
	Console.WriteLine("Second date comes earlier.");

The output of the above code will look like this:

Second date comes earlier.
Second date comes earlier.

Number of days in a Month

A common problem is to find the number of days in any month in the future or the past. For instance, you might want to get the number of days in the second month of the year 2005. In such cases, C# provides DaysInMonth function. The function takes two arguments: The year and the month in integer form. Take a look at the following example.

int NumberOfDays = DateTime.DaysInMonth(2004, 2);

The above code finds the number of days for February 2004. Since 2004 was a leap year, the number of days for February will be 29 which you will see in the output.

This article presents a brief introduction to some of the most fundamental concepts related to usage of date and time in C#. If you found this article helpful be sure to check out my C# Roadmap. Happy coding!