Working with Dates and Times in C#

.NET programming topics
Post Reply
Cyclops
Lieutenant
Lieutenant
Posts: 71
Joined: Wed Jul 15, 2009 1:48 pm
Location: London

Working with Dates and Times in C#

Post by Cyclops » Thu Nov 12, 2009 2:52 pm

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.

Code: Select all

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.
pecifier : 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"
Post Reply

Return to “.NET Programming”