This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET Framework
.NET 1.1+

DateTime Manipulation

The twenty-seventh part of the C# Fundamentals tutorial completes the examination of the DateTime data type provided by C# and the .NET Framework. This article considers manipulation of DateTime data and formatting date and time information as a string.

DateTime Value Manipulation

The previous articles in the C# Fundamentals tutorial have examined the creation and reading of DateTime data and the structure's constituent parts. In this article we will manipulate DateTime information, starting by adjusting DateTime values. This can be achieved using simple operators or, for more detailed control, using DateTime methods.

Addition and Subtraction Operators

Two arithmetic operators can be used with the DateTime structure. These are addition (+) and subtraction (-). Each requires two operands. The first is the DateTime value to modify and the second is a TimeSpan containing the amount of time to add or remove.

DateTime theDate = DateTime.Parse("2 Jan 2007 20:15:00");

// Add one hour, one minute and one second
theDate = theDate + new TimeSpan(1, 1, 1);    // theDate = 2 Jan 2007 21:16:01

// Subtract twenty-five days
theDate = theDate - new TimeSpan(25, 0, 0, 0);  // theDate = 8 Dec 2006 21:16:01

The two arithmetic operators may also be used as compound assignment operators. The following demonstrates this after using the Parse method to create a TimeSpan value from a string.

DateTime theDate = DateTime.Parse("2 Jan 2007 20:15:00");

// Add one hour, one minute and one second
theDate += TimeSpan.Parse("01:01:01");        // theDate = 2 Jan 2007 21:16:01

// Subtract twenty-five days
theDate -= TimeSpan.Parse("25.00:00:00");     // theDate = 8 Dec 2006 21:16:01

Add Methods

The Add methods allow more control over the processing of DateTime values. The first of which is the Add method itself, which adds a TimeSpan to a DateTime:

DateTime theDate = DateTime.Parse("2 Jan 2007 20:15:00");
TimeSpan duration = TimeSpan.Parse("1.01:01:01");

theDate = theDate.Add(duration);              // theDate = 3 Jan 2007 21:16:01

The Add method provides no greater control over the calculation than the simple arithmetic operators. To gain flexibility, we can use methods for adding a number of years, months, etc. There is even an Add method used to add ticks; a single tick being one ten-millionth of a second. These methods are all named Add followed by the unit of time to be added. Values may be subtracted by passing a negative parameter to an Add method. Each method accepts a single double-precision number as a parameter except for AddTicks, which requires a long integer parameter.

DateTime theDate = DateTime.Parse("2 Jan 2007");

theDate = theDate.AddYears(1);                // theDate = 2 Jan 2008
theDate = theDate.AddMonths(2);               // theDate = 2 Mar 2008
theDate = theDate.AddDays(1.5);               // theDate = 3 Mar 2008 12:00:00
theDate = theDate.AddHours(-6);               // theDate = 2 Mar 2008 06:00:00
theDate = theDate.AddMinutes(150);            // theDate = 2 Mar 2008 08:30:00
theDate = theDate.AddSeconds(10.5);           // theDate = 2 Mar 2008 08:30:10.5
theDate = theDate.AddMilliseconds(499);       // theDate = 2 Mar 2008 08:30:10.999
theDate = theDate.AddTicks(10000);            // theDate = 2 Mar 2008 08:30:11

Subtract Method

The Subtract method provides similar function to the basic Add method. However, it can be used in two ways. Firstly, a TimeSpan may be subtracted from a DateTime to return a new DateTime. Secondly, one DateTime value may be subtracted from another to obtain the time difference as a TimeSpan.

DateTime theDate = DateTime.Parse("2 Jan 2007");
TimeSpan subtract = TimeSpan.Parse("1.01:00:00");
DateTime startDate = DateTime.Parse("1 Jan 2007");
DateTime endDate = DateTime.Parse("2 Jan 2007 12:00:00");
TimeSpan diff;

// Subtract a TimeSpan from a DateTime
theDate = theDate.Subtract(subtract);         // theDate = 31 Dec 2006 23:00:00

// Find the difference between two dates
diff = endDate.Subtract(startDate);           // diff = 1.12:00:00

NB: In the above example the difference between the dates is positive because the DateTime being subtracted is earlier than that being subtracted from. If the reverse were true then the result would be negative.

UTC and Local DateTime Conversion

The DateTime structure allows the storage of Co-ordinated Universal Time (UTC) and local time values. You can also convert between these values using the ToUniversalTime and ToLocalTime methods. For the following example, Rangoon has been selected in the Window's time zone settings for its interesting six and a half hour offset from UTC.

DateTime localDate = DateTime.Parse("1 Jul 2007 12:00");
DateTime utcDate = localDate.ToUniversalTime();     // 1 Jul 2007 05:30
DateTime rangoon = utcDate.ToLocalTime();           // 1 Jul 2007 12:00

Conversion from DateTime to String

The DateTime structure provides several methods to achieve a conversion of date and time information to strings, which are ideal for display purposes.

Basic Conversions

When Microsoft Windows is installed, the user selects the region of the world where they live. This information is used to determine how dates and times are formatted. Some users may customise their settings to achieve their preferences for long and short dates and times. As developers, we should honour their selections by ensuring that output from our programs uses these settings.

The DateTime structure provides four methods for converting DateTime values to strings. Each allows the automatic generation of a string containing a long or short date or time. The names of the methods are ToLongDateString, ToShortDateString, ToLongTimeString and ToShortTimeString. None of the functions have parameters.

NB: The following example assumes that the code is executing on a UK machine. The results in other countries or on customised systems may differ.

DateTime theDate = DateTime.Parse("3 Jan 2007 21:25:30");
string result;

result = theDate.ToLongDateString();          // result = "03 January 2007"
result = theDate.ToShortDateString();         // result = "03/01/2007"
result = theDate.ToLongTimeString();          // result = "21:25:30"
result = theDate.ToShortTimeString();         // result = "21:25"
3 January 2007