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

From Techotopia
Jump to: navigation, search
(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...)
(No difference)

Revision as of 20:16, 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.

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


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:

AddMonthsAddSecondsAddYears
MethodDescription
AddAdds the value of the specified TimeSpan object instance.
AddDaysAdds the specified number of days
AddHoursAdds the specified number of hours
AddMillisecondsAdds the specified number of Milliseconds
AddMinutesAdds the specified number of minutes
Adds the specified number of months
Adds the specified number of seconds
Adds the specified number of years