Changes

Jump to: navigation, search

Working with Dates and Times in C Sharp

2,659 bytes added, 20:16, 19 February 2008
New page: It is a rare application that can be developed without in some way needing to work with dates and times. In recongition of this fact, Microsoft engineers responsible for C# gave us the ''D...
It is a rare application that can be developed without in some way needing to work with dates and times. In recongition of this fact, Microsoft engineers responsible for C# gave us the ''DateTime'' object. In this chapter we will look in detail at using this object to work with dates and times in C# based applications.

== Creating a C# Date Time Object ==

The first step in using the DateTime object when working with dates and times in C# is to create an object instance. This may achieved using the ''new'' keyword passing through year, month and day values. For example, to create a DateTime object preset to September 22, 2008 the following code would need to be written:

<pre>
using System;

class TimeDemo
{
static void Main()
{
DateTime meetingAppt = new DateTime(2008, 9, 22);
System.Console.WriteLine (meetingAppt.ToString());
}
}
</pre>

In the above example, after setting the date we use the ''ToString()'' method of the DateTime object to output the current date and time value as a string.

It is important to note that if a time is not specified along with the date, the DateTIme class constructor will set the time to 12:00am. With this in mind, the above code will output the following text:

<pre>
9/22/2008 12:00:00 AM
</pre>

Time values are specified by passing through hours, minutes and seconds values to the constructor. For example, to set the time to 14:30:00:

<pre>
using System;

class TimeDemo
{
static void Main()
{
DateTime meetingAppt = new DateTime(2008, 9, 22, 14, 30, 0);
System.Console.WriteLine (meetingAppt.ToString());
}
}
</pre>

Resulting in generation of the following output:

<pre>
9/22/2008 2:30:00 PM
</pre>

== Getting the Current System Time and Date ==



== Adding or Subtracting from Dates and Times ==

The C# DateTime object provides a number of methods for adding or subtracting date and times from a DateTime object instance. These methods are outlined the following table:

<table border="1" cellspacing="0">
<tr style="background:#efefef;">
<th>Method<th>Description</th>
</tr>
<tr>
<td>Add<td>Adds the value of the specified TimeSpan object instance.</td>
<tr>
<td>AddDays<td>Adds the specified number of days</td>
<tr>
<td>AddHours<td>Adds the specified number of hours</td>
<tr>
<td>AddMilliseconds<td>Adds the specified number of Milliseconds</td>
<tr>
<td>AddMinutes<td>Adds the specified number of minutes</td>
<tr>
<tr>AddMonths<td>Adds the specified number of months</td>
<tr>
<tr>AddSeconds<td>Adds the specified number of seconds</td>
<tr>
<tr>AddYears<td>Adds the specified number of years</td>
</tr>
</table>

Navigation menu