Working with Dates and Times in C Sharp

From Techotopia
Revision as of 14:41, 5 May 2016 by Neil (Talk | contribs) (Text replacement - "<table border="0" cellspacing="0" width="100%">" to "<table border="0" cellspacing="0">")

Jump to: navigation, search
PreviousTable of ContentsNext
Formatting Strings in C#C# and Windows Forms


Purchase and download the full PDF and ePub versions of this Visual C# eBook for only $9.99


It is a rare application that can be developed without in some way needing to work with dates and times. In recognition of this fact, the 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. Topics covered include adding and subtracting time, getting the system date and time and formatting and extracting elements of dates and times in C#.


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

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:

<google>ADSDAQBOX_FLOW</google>

MethodDescription
AddAdds/Subtracts the value of the specified TimeSpan object instance.
AddDaysAdds/Subtracts the specified number of days
AddHoursAdds/Subtracts the specified number of hours
AddMillisecondsAdds/Subtracts the specified number of Milliseconds
AddMinutesAdds/Subtracts the specified number of minutes
AddMonthsAdds/Subtracts the specified number of months
AddSecondsAdds/Subtracts the specified number of seconds
AddYearsAdds/Subtracts the specified number of years

A 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:

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 distinct and separate values, namely the day, month, year, hours, minutes, seconds and milliseconds. The C# DateTime object stores each of these values as a separate property within 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

Formatting 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 predefined formatting methods or customized with an almost infinite number of variations using the ToString() method.

The basic formatting methods operate as follows:

  DateTime meetingAppt = new DateTime(2008, 9, 22, 14, 30, 0);

  System.Console.WriteLine(meetingAppt.ToLongDateString());   // Monday, September 22, 2008
  System.Console.WriteLine(meetingAppt.ToShortDateString());  // 9/22/2008
  System.Console.WriteLine(meetingAppt.ToShortTimeString());  // 2:30 PM

If the above prepackaged formatting methods do not provide the required output, a formidable variety of custom formats may be constructing using the ToString() method. The ToString() method takes as an argument a format string which specifies precisely how the date and time is to be displayed. The following example shows a few of this formats in action. The subsequent table lists all the possible format variables which may be used:

   DateTime meetingAppt = new DateTime(2008, 9, 22, 14, 30, 0);

   System.Console.WriteLine(meetingAppt.ToString("MM/dd/yy")); // 09/22/08

   System.Console.WriteLine(meetingAppt.ToString("MM - dd - yyyy")); // 09 - 22 - 2008

   System.Console.WriteLine(meetingAppt.ToString("ddd dd MMM yyyy")); // Mon 22 Sep 2008

   System.Console.WriteLine(meetingAppt.ToString("dddd dd MMMM yyyy")); // Monday September 22 2008

The full list of format patterns support by the ToString() method of the C# DateTime class is as follows:

Format SpecifierDescription
d The day of the month. Single-digit days will not have a leading zero.
dd The day of the month. Single-digit days will have a leading zero.
ddd The abbreviated name of the day of the week, as defined in AbbreviatedDayNames.
dddd The full name of the day of the week, as defined in DayNames.
M The numeric month. Single-digit months will not have a leading zero.
MM The numeric month. Single-digit months will have a leading zero.
MMM The abbreviated name of the month, as defined in AbbreviatedMonthNames.
MMMM The full name of the month, as defined in MonthNames.
y The year without the century. If the year without the century is less than 10, the year is displayed with no leading zero.
yy The year without the century. If the year without the century is less than 10, the year is displayed with a leading zero.
yyyy The year in four digits, including the century.
gg The period or era. This pattern is ignored if the date to be formatted does not have an associated period or era string.
h The hour in a 12-hour clock. Single-digit hours will not have a leading zero.
hh The hour in a 12-hour clock. Single-digit hours will have a leading zero.
H The hour in a 24-hour clock. Single-digit hours will not have a leading zero.
HH The hour in a 24-hour clock. Single-digit hours will have a leading zero.
m The minute. Single-digit minutes will not have a leading zero.
mm The minute. Single-digit minutes will have a leading zero.
s The second. Single-digit seconds will not have a leading zero.
ss The second. Single-digit seconds will have a leading zero.
f The fraction of a second in single-digit precision. The remaining digits are truncated.
ff The fraction of a second in double-digit precision. The remaining digits are truncated.
fff The fraction of a second in three-digit precision. The remaining digits are truncated.
ffff The fraction of a second in four-digit precision. The remaining digits are truncated.
fffff The fraction of a second in five-digit precision. The remaining digits are truncated.
ffffff The fraction of a second in six-digit precision. The remaining digits are truncated.
fffffff The fraction of a second in seven-digit precision. The remaining digits are truncated.
t The first character in the AM/PM designator defined in AMDesignator or PMDesignator, if any.
tt The AM/PM designator defined in AMDesignator or PMDesignator, if any.
z The time zone offset ("+" or "-" followed by the hour only). Single-digit hours will not have a leading zero. For example, Pacific Standard Time is "-8".
zz The time zone offset ("+" or "-" followed by the hour only). Single-digit hours will have a leading zero. For example, Pacific Standard Time is "-08".
zzz The full time zone offset ("+" or "-" followed by the hour and minutes). Single-digit hours and minutes will have leading zeros. For example, Pacific Standard Time is "08:00". : The default time separator defined in TimeSeparator. / The default date separator defined in DateSeparator.
% c - Where c is a format pattern if used alone. The "%" character can be omitted if the format pattern is combined with literal characters or other format patterns.
\ c - Where c is any character. Displays the character literally. To display the backslash character, use "\\".


Purchase and download the full PDF and ePub versions of this Visual C# eBook for only $9.99



PreviousTable of ContentsNext
Formatting Strings in C#C# and Windows Forms