Every software engineer can testify that all kinds of projects, regardless of their purpose or how simple the requirements seem to be, deal with dates and mostly times. Fortunately, C# has built-in methods and properties that make our lives much easier. In this article we will present some of the most common techniques to manage and work with date and time variables.
Before we begin, you should be also informed that there are numerous other how-to articles covering various topics from the Windows registry up to regular expressions, lossless image conversion and resizing, working with collections, and more, published already here at ASP Free under the C# category. Be sure to check those out.
At the beginning of this article we will introduce the foundation concepts that must be understood in order to learn the rest. We will present the DateTime structure located in theSystemnamespace. Moving on, its properties, methods, and constructors will also be explained thoroughly and also illustrated with examples (such as code samples with output).
This guide assumes familiarity with the C# syntax, but not with dates/times. It does not target professional coders, but rather those who are now learning how to code in C#. It's a great language to begin with; there's plenty of documentation along with proactive communities on various forums.
Thus, if you are ready to learn the basics of date and time handling in C# that are going to serve as a solid ground foundation to your further researches, let's begin! We are going to focus on explaining how to do the most necessary tasks such as assigning date and time, how to compare them with each other, various format conversions, and ultimately specific value extraction (such as part of a date).
The DateTime structure has been included ever since the first .NET Framework. It can be found within the System namespaces. It is one of the most generic and straightforward objects to work with. It's not exactly a class, but simply a structure, even though it's a collection of methods, properties, values, and operators. With the help of this structure we can represent an instant in time, whether it is a date, time, or any other related action.
It should be said that this kind of structure can store any date (along with a time) from 00:00:00, January, 1, 0001 A.D. up to 23:59:59, December, 31, 9999 A.D. Without any reasonable doubts, we can claim that this range should suffice.
The real power of the DateTime structure lies in its plethora of built-in methods. Usually we need to work with dates and times, not just store and retrieve them. And libraries were designed for this very purpose-to increase the productivity of developers by providing them with ready-to-use pre-coded functions/methods.
On this page we are going to see how we can create a new DateTime struct, initialize it with some data, and then retrieve it later. Once we have learned how to do these tasks, then we can look into its methods and useful operators.
Before we begin, please remember that the name of the structure is DateTime; as its name suggests, it always holds both date and time values. You cannot store just one or the other. These two go together. All right, now let's call the constructor!
DateTime objDate1 = new DateTime(2008, 9, 28, 2, 20, 35);
DateTime objDate2 = new DateTime.Now;
DateTime objDate3 = new DateTime.Today;
string strDate = "09/28/2008 02:20:35 AM";
DateTime objDate4 = new DateTime.Parse(strDate);
The above examples should make sense right away. Using the properties Today and Now we can get these values from the local computer (depending upon the time zone). You can use the SpecifyKind() method when creating a new DateTime structure, but you want to explicitly specify its kind (such as UTC, local time, or neither). Calling the constructor without any parameters simply creates the first A.D. possible date in range.
The constructor can be overloaded with as many details as necessary (or less than that; just the year is also possible). You can set up a date using all of its parameters such as year, month, day, hours, minutes, and seconds. Then again, what if you want to convert a string into a DateTime structure? If this is what you want, then the Parse() method is what you're going to need. You may want to look into the ParseExact() method, too.
Furthermore, both Parse() and ParseExact() will throw an exception if the conversion fails (i.e.; the supplied string doesn't complies with the required format). If you want a work-around for this, then the TryParse() and TryParseExact() methods might be better options for you. These return a Boolean whether the conversion succeeds or not without throwing an exception.
Should you supply only three parameters to the constructor, without specifying the exact time, it defaults to a value of midnight. Furthermore, there's another way to load the constructor, and that's using 64-bit integer ticks as the only parameter. This value is counted since January 1st of the year 1 A.D, and it measures the total count of 100-nanoseconds ticks since the beginning of the Gregorian calendar.
There are two interesting static properties: MinValue and MaxValue. These two always return the minimum and maximum possible DateTime value, respectively, from that aforementioned range (year 1 and 9999). They are usually used for comparison tasks (such as assigning any non-null value for a date-time variable).
In the next section we're going to discuss operators such as subtraction, addition, and, of course, lots of other useful methods and properties that we're going to need.
Performing various operations with dates is something that we encounter during our programming endeavors. First, let's understand the basics. There are two functions, namely Add() and Subtract(), which we are going to present on this page. The similarity between these two is that neither actually modifies the current DateTime structure; rather, they just return another DateTime structure with new values.
In order to get around this, often when the specific DateTime structure ought to be modified, we apply this technique in the following fashion (code sample below). Please notice that we're introducing a new TimeSpan structure, which is going to be used as the parameter of Add. The TimeSpan structure behaves just like DateTime. Its purpose is to represent time intervals. We're adding that interval to our DateTime structure.
The major difference between the DateTime and TimeSpan structures is that the former describes an exact time and date at a given moment-it's instant; while the latter represents a time interval-it's an amount. Subtracting two DateTime structures from each other becomes instantly a TimeSpan structure.
DateTime objDate1 = new DateTime.Now;
DateTime objDate2 = new DateTime.UtcNow;
TimeSpan tsDiff = new tsDiff.Parse(objDate1 - objDate2);
objDate1 = objDate1.Add(tsDiff);
There are numerous other variations of the Add method, such as the AddYears(), AddMonths(), AddDays(), AddHours(), AddMinutes(), AddSeconds(), AddTicks(), and so forth. The same applies to the Subtract() methods, too. Additionally, you can use simple arithmetic operators. For example:
objDate1 = objDate1 + objDate2; // using traditional assignment
objDate1 += objDate2; // using compact compound assignment i.e. +=
Lately it's become quite common to be working within multinational corporations that are outsourcing dozens of projects literally everywhere. Multi-language support has become necessary, as well as the seamless integration of numerous time zones.
In order to maintain our successful edge, we also need to learn how to accomplish conversions between local times and UTC. There are two universal methods which can help us out: ToLocalTime() and ToUniversalTime(), respectively. These methods work based on offsets; the structure itself cannot store whether a DateTime object is UTC or LocalTime. Therefore, be sure to double check the ways in which you rely on them.
These methods as well as the LocalTime and UTC properties grab the settings out of your operating system, and if that is configured incorrectly, then the entire sand castle falls apart. Another important concept that we would find useful to know is formatting. There are various scenarios where we must adhere to strict rules according to which we need to print out or read in dates and times. So let's see what we can do.
First, as we have already seen, the DateTime structure is composed of a date and time segment. These two segments have roughly three elements, meaning year, month, day, and hour, minutes, seconds, respectively (ignoring things like milliseconds). To format the output the way we need, we almost always need to begin with breaking these two main segments into individual parts, the date and the time.
Once we end up with these as stand-alone parts, we can rely on numerous formatting methods to explicitly specify the style, fashion, trend, or simply culture to which we want the output to conform. The ToString() method converts the DateTime object into its exact full string representation. This is great when we want both parts. It also supports lots of extra formatting options if we rely on its formatting specifiers.
Here's the entire list of specifiers - for a more detailed explanation, read the MSDN.
Specifier : Example
d : 10/28/2008
D : Sunday, September 28, 2008
f : Sunday, September 28, 2008 10:35 PM
F : Sunday, September 28, 2008 10:35:23 PM
g : 9/28/2008 10:35 PM
G : 9/28/2008 10:35:23 PM
m : September 28
o : 2008-09-28T22:35:07.0000000
R : Sun, 28 Sep 2008 22:35:23 GMT
s : 2008-09-28T22:35:23
t : 10:35 PM
T : 10:35:23 PM
u : 2008-09-28 22:35:23Z
U : Sunday, September 28, 2008 7:35:23 PM
y : September, 2008
'h:mm:ss.ff t': 10:35:23.00 P
'd MMM yyyy': 28 Sep 2008
'HH:mm:ss.f': 22:35:23.0
'dd MMM HH:mm:ss': 28 Sep 22:35:23
'Month: M': Month: 9
'HH:mm:ss.ffffzzz': 22:35:23.0000+03:00
However, this method has a few variations: ToLongDateString() - converts the object to long date string representation; ToShortDateString() - converts it to short date string; ToLongTimeString() - does the conversion to long time string representation; ToShortTimeString() - does the same, but to short time string. These methods focus on either of the segments (date and time, respectively).
Check out the example below; and as always make sure to check out the MSDN.
Long date pattern: "dddd, MMMM dd, yyyy"
Long date string: "Sunday, September 29, 2008"
Long time pattern: "h:mm:ss tt"
Long time string: "1:21:30 AM"
Short date pattern: "M/d/yyyy"
Short date string: "9/29/2008"
Short time pattern: "h:mm tt"
Short time string: "1:21 AM"
And finally, you should thoroughly examine the entire list of custom date and time format specifiers from this page at MSDN. Basically, you will gain an enormous amount of flexibility, because you can format your dates and times as far as your imagination stretches.
We have arrived to the end of this tutorial. Hopefully by now you've acquired the necessary know-how to fully comprehend the MSDN documentation when the situation asks for it, and to figure out your way around when the scenario seems tough. The purpose of this article was to give you a brief overview of the possibilities that are built into the .NET Framework to aid us with our date/time related routine tasks.
Moreover, as mentioned earlier, you must understand that we cannot include each and every method, property, and operator that is part of the DateTime structure. It's up to you to head over to the official MSDN documentation and learn how to use them. However, this article definitely had given you a sense of what to expect and how to implement the rest of the "leftover" properties and methods. Practice, practice... code!
The road that leads to computer programming excellent simply never ends. The best way to learn and acquire lots of new knowledge and experience is by researching, experimenting, and studying as you go. When you face a seemingly tough problem, and you do your best to find either a solution or a workaround, then you have surely learned that specific "technique" for an entire lifetime. So just never give up...
Finally, I'd like to invite you to join our ever-growing and friendly community of tech professionals at Dev Hardware Forums. We focus on all areas of IT&C starting from hardware, software, up to consumer electronics and around-the-clock IT news. You might also want to check out the forums of our sister site at Dev Shed covering programming-related topics as well as ASP Free which focuses on Microsoft content.