Difference between revisions of "Working with Dates and Times in C Sharp"

From Techotopia
Jump to: navigation, search
(Adding or Subtracting from Dates and Times)
(Getting the Current System Time and Date)
Line 49: Line 49:
 
== Getting the Current System Time and Date ==
 
== Getting the Current System Time and Date ==
  
 +
The system date and time of the computer on which the C# code is executing may be accessed using the ''Today'' and ''Now'' static properties of the DateTime class. The ''Today'' property will return the current system date (and also the time set to 12:00 AM) whilst the ''Now'' property returns the current date and time.
  
 +
For example:
 +
 +
<pre>
 +
using System;
 +
 +
class TimeDemo
 +
{
 +
      static void Main()
 +
      {
 +
 +
            System.Console.WriteLine (DateTime.Today.ToString()
 +
 +
            System.Console.WriteLine (DateTime.Now.ToString());
 +
      }
 +
}
 +
</pre>
 +
 +
== Formating Dates and Times in C# ==
 +
 +
There are number of techniques available for extracting and displaying dates and times in particular formats. Output may be configured using a small number of predifined formatting methods or customized with an almost infinite number of variations using the ToString() method.
 +
 +
The basic formatting methods operate as follows:
 +
 +
<pre>
  
 
== Adding or Subtracting from Dates and Times ==
 
== Adding or Subtracting from Dates and Times ==

Revision as of 20:58, 19 February 2008

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.


Contents


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:

using System;

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

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:

9/22/2008 12:00:00 AM

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:

using System;

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

Resulting in generation of the following output:

9/22/2008 2:30:00 PM

Getting the Current System Time and Date

The system date and time of the computer on which the C# code is executing may be accessed using the Today and Now static properties of the DateTime class. The Today property will return the current system date (and also the time set to 12:00 AM) whilst the Now property returns the current date and time.

For example:

using System;

class TimeDemo
{
       static void Main()
       {

            System.Console.WriteLine (DateTime.Today.ToString()

            System.Console.WriteLine (DateTime.Now.ToString());
       }
}

Formating Dates and Times in C#

There are number of techniques available for extracting and displaying dates and times in particular formats. Output may be configured using a small number of predifined formatting methods or customized with an almost infinite number of variations using the ToString() method.

The basic formatting methods operate as follows:


== 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/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());
       }
}

the above code, will generate the following output, showing a date 5 days into the future from our original date and time:

9/27/2008 14:30:00 PM

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:

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());
       }
}

Resulting in the following output:

11/22/2007 2:30:00 PM

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:

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);
       }
}

When compiled and executed the above code will generate the following output:

22
9
2008
14
30
0
0

Basic Formatting and Dates and Times