Changes

Jump to: navigation, search

Working with Dates and Times in C Sharp

2,390 bytes added, 20:32, 19 February 2008
Adding or Subtracting from Dates and Times
</tr>
<tr>
<td>Add<td>Adds /Subtracts the value of the specified TimeSpan object instance.</td>
<tr>
<td>AddDays<td>Adds /Subtracts the specified number of days</td>
<tr>
<td>AddHours<td>Adds /Subtracts the specified number of hours</td>
<tr>
<td>AddMilliseconds<td>Adds /Subtracts the specified number of Milliseconds</td>
<tr>
<td>AddMinutes<td>Adds /Subtracts the specified number of minutes</td>
<tr>
<td>AddMonths<td>Adds /Subtracts the specified number of months</td>
<tr>
<td>AddSeconds<td>Adds /Subtracts the specified number of seconds</td>
<tr>
<td>AddYears<td>Adds /Subtracts the specified number of years</td>
</tr>
</table>
 
An key issue to understand is that these methods do not change the value of the DateTime object on which the method is called, but rather return a new DateTime object primed with the modified date and time. For example, to add 5 days to our example:
 
<pre>
using System;
 
class TimeDemo
{
static void Main()
{
DateTime meetingAppt = new DateTime(2008, 9, 22, 14, 30, 0);
DateTime newAppt = meetingAppt.AddDays(5);
System.Console.WriteLine (newAppt.ToString());
}
}
</pre>
 
the above code, will generate the following output, showing a date 5 days into the future from our original date and time:
 
<pre>
9/27/2008 14:30:00 PM
</pre>
 
To subtract from a date and time simply pass through a negative value to the appropriate method. For example, to subtract 10 months from our example object:
 
<pre>
using System;
 
class TimeDemo
{
static void Main()
{
DateTime meetingAppt = new DateTime(2008, 9, 22, 14, 30, 0);
DateTime newAppt = meetingAppt.AddMonths(-10);
System.Console.WriteLine (newAppt.ToString());
}
}
</pre>
 
Resulting in the following output:
 
<pre>
11/22/2007 2:30:00 PM
</pre>
 
== Retrieving Parts of a Date and Time ==
 
Dates and times are comprised of distint and seperate values, namely the day, month, year, hours, minutes, seconds and milliseconds. The C# DateTime object stores each of these values is a separate property with the object allowing each to be accessed individually. The following code sample extracts each value and displays it in the console window:
 
<pre>
using System;
 
class TimeDemo
{
static void Main()
{
DateTime meetingAppt = new DateTime(2008, 9, 22, 14, 30, 0);
 
System.Console.WriteLine (meetingAppt.Day);
System.Console.WriteLine (meetingAppt.Month);
System.Console.WriteLine (meetingAppt.Year);
System.Console.WriteLine (meetingAppt.Hour);
System.Console.WriteLine (meetingAppt.Minute);
System.Console.WriteLine (meetingAppt.Second);
System.Console.WriteLine (meetingAppt.Millisecond);
}
}
</pre>
 
When compiled and executed the above code will generate the following output:
 
<pre>
22
9
2008
14
30
0
0
</pre>
 
== Basic Formatting and Dates and Times ==

Navigation menu