Jeremy Shanks
Spread the Knowledge!

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#.

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:

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.

The output of the above code should look like this:

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.

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:

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.

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.

The output of the above code will look like this:

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.

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!

About the Author Jeremy Shanks

Hi, my name is Jeremy Shanks. I am a Software Engineer in Raleigh, NC. Recently I embarked on the journey of teaching others how to develop projects in C#. Be sure to check them out if you are new to C#.

follow me on:
>