Home

Dates and Times

 

Dates and Times

 

Introduction

A date is a measure of non-spatial units that have elapsed in a set period. To perform this measure, a certain point is set and called midnight. From that point, a number of units are counted until the next corresponding point is reached. Because the light in daily life changes from one midnight unit to the next midnight unit, the sub-point when the light shows up, or starts, is called sunrise. The sub-point when the light diminishes or starts disappearing is called sunset. The midpoint between the sunrise and the sunset is called noon. The first part, from midnight to noon is referred to as AM in US English. The other part is referred to as PM in US English.

The group of units between two midnight points is called a day. The days are counted from 0, 1, and up. A group of seven consecutive days is called a week. The weeks are counted from 1 and up. To make it easy to identify a day, the days of a week are named as Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, and Sunday. These are referred to as long names. The corresponding short names are Mon, Tue, Wed, Thu, Fri, Sat, and Sun. The day considered as the first of the week depends on the language and/or some other considerations. For example, in US English, Sunday is usually considered the first day of the week.

Most of the time, a group of four weeks is called a month. The months are counted from 1 and up. To make it easy to identify a month, each holds a long name and they are January, February, March, April, May, June, July, August, September, October, November, and December. Their short names are Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, and Dec. Except for the month of February that depends on a factor named Leap Year, the maximum days of each month are January=31, March=31, April=30, May=31, June=30, July=31, August=31, September=30, October=31, November=30, and December=31.

A group of three months is called a trimester. A group of four months is called a quarter. A group of six months is called a semester. A group of twelve months is called a year. The years are counted from 1 and up (some compilers or applications specify when the years start; for example, some applications start their count at 1901 and cannot process years below that numbers; some other applications would not process a year beyond a certain year). The .NET Framework compilers count the years from 0001 to 9999.

In a regular year, the months are counted from 1 to 12. The technique or expression used to identify a particular day during a year is called a date. The days are counted from 1 to 365 or 366 (depending on a factor called a leap year). A date can be the combination of a day, its months, and the year. There are other aspects that can be taken into consideration. We will address them when necessary.

A unit of measure in a day is called a second. The seconds are counted from 0 to 59 or from 0, 1, 2, and so on. In some applications, when precision is particularly important, a second is considered a group of 1000 portions called milliseconds. The milliseconds are counted from 0 to 999.

A group of 60 seconds is called a minute. A group of 60 minutes is called an hour. A group of 24 hours is called a day. The technique or expression used to identify a particular unit of measure during a day is called the time. It can be the combination of the hour, the minute, and the second. Some other aspects may be taken into consideration. We will review them as we move on.

Date Time Value Creation

To represent the dates, computers, applications, and compilers are configured with specific techniques. In Microsoft Windows, to manage dates, the operating system provides a structure named SYSTEMTIME. To manage dates, the .NET Framework provides the DateTime structure. To create a date or a time value, you can first declare DateTime variable. To assist you with initializing the variable, the DateTime structure is equipped with various constructors.

The default constructor allows you to create a date or a time object without specifying its details. This would be done as follows:

using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime tm = new DateTime();

            return 0;
        }
    }
}

After declaring a DateTime variable and initializing it, it holds all necessary pieces of information about its date and its time values.

The Characteristics of a Date-Time Value

You can access the information using the variable. The pieces of information are represented by properties of the DateTime structure and they are:

  • Month: The Month property is the numeric value, between 1 and 12, of the month of the variable
  • Day: The Day property is the numeric value of the day in the Month value of the variable. Depending on the month, the value is between 1 and 31. For example, if the variable's value is April 6, 2002, the Day value is 6
  • DayOfWeek: The DayOfWeek property is the name of the Day value of the variable. The name is a member of the DayOfWeek enumeration whose members are Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday. Because the members are listed without a re-definition of their default indexes, the index of Sunday is 0 and the index of Saturday is 6
  • Year: The Year property is the numeric value of the year of the variable
  • DayOfYear: The DayOfYear is the number that represents the ranking day inside of the Year value of the variable. For example, if the variable's value is February 6, 2002, the DayOfYear value is 31 + 6 = 37
  • Date: The Date property is the combination of the Month, the Day, and the Year values of the variable
  • Hour: The Hour is the numeric value of the hour, between 0 and 23, of the time component of the variable
  • Minute: The Minute is the numeric value of the minute inside of the Hour value of the variable. It is a value between 0 and 59 
  • Second: The Second is the numeric value of the second inside of the Minute value of the Hour value. It is a value between 0 and 59
  • Millisecond: The Millisecond is the numeric value of the millisecond inside of the Second value of the Minute part of the Hour section of the variable. It is a value between 0 and 999

The Default Date and Time Values

The default constructor of the DateTime structure initializes the date to January 1st, 0001 and the time at midnight (01:01:01). This is illustrated in the following program:

using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime tm = new DateTime();

            Console.WriteLine("Default Date and Time: {0}", tm);
            return 0;
        }
    }
}

This would produce:

Default Date and Time: 1/1/0001 12:00:00 AM
Press any key to continue . . .

This also means that the lowest date and time values that a DateTime object can hold is January 1st, 0001 at 00:00:00. This value is represented by the MinValue constant member of the DateTime structure. The highest date and time that a DateTime object can hold in the structure is called MaxValue and it is set at December 31, 9999.

Dates

 

Date Creation

A date is a technique of identifying a period using three numbers: the year, the month, and the day. Each is an integer value. If you know the values you want to use to create or specify a date value, when declaring a DateTime variable, you can use the following constructor:

public DateTime(int year, int month, int second);

Here is an example of creating a date:

using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime ind = new DateTime(1960, 1, 1);

            Console.WriteLine("Independence Day: {0}", ind);
            return 0;
        }
    }
}

This would produce:

Independence Day: 1/1/1960 12:00:00 AM
Press any key to continue . . .

Converting a String to Date

Before displaying a DateTime value in your application, you can first convert it to a string. To support this, the DateTime structure provides the ToString() method that is overloaded with various versions. One of the versions takes no argument and its syntax is:

public override string ToString();

If you call this version of the method, the compiler uses a default format depending on the language set on the user's computer. If you want to control how the date should be rendered, you can use the version of the ToString() method that takes as argument a String value.

Rules of Date Formats

The computer uses two main categories of date display. These categories are based on the language used by your computer. For example, most user computers that reside in the United States use a standard known as US English. This commands how the date displays in the continental US. Each category uses specific characters to represent its value:

Format Description
MM The double M (in uppercase) string gets the numeric value of the month from 1 to 12. If the number is less than 10, it would display with the leading 0. Here is an example:
using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime date = new DateTime(2002, 4, 22);
            string strMonth = date.ToString("MM");

            Console.WriteLine("Date and Time: {0}", date);
            Console.WriteLine("Month Value:   {0}\n", strMonth);
            return 0;
        }
    }
}

This would produce:

Date and Time: 4/22/2002 12:00:00 AM
Month Value:   04

Press any key to continue . . .

It the number is higher than 9, it would display so.

MMM The triple M as MMM (in uppercase) gets the name of the month using three letters. This variable is defined by the operating system. The names of the month in US English are Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, and Dec. Here is an example:
using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime date = new DateTime(1998, 1, 12);
            string strMonth = date.ToString("MMM");

            Console.WriteLine("Date and Time: {0}", date);
            Console.WriteLine("Month Name:    {0}\n", strMonth);
            return 0;
        }
    }
}

This would produce:

Date and Time: 1/12/1998 12:00:00 AM
Month Name:    Jan

Press any key to continue . . .
MMMM The quadruple M as MMMM (in uppercase) gets the complete name of a month as defined by the operating system of the user's computer. The names of the months are January, February, March, April, May, June, July, August, September, October, November, and December.
Here is an example:
using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime date = new DateTime(2004, 10, 23);
            string strMonth = date.ToString("MMMM");

            Console.WriteLine("Date and Time: {0}", date);
            Console.WriteLine("Month Name:    {0}\n", strMonth);
            return 0;
        }
    }
}

This would produce:

Date and Time: 10/23/2004 12:00:00 AM
Month Name:    October

Press any key to continue . . .
dd The double d gets the numeric day of the month. If the number is less than 10, it would display with a leading 0. Here is an example:
using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime date = new DateTime(2002, 4, 2);
            string strDay = date.ToString("dd");

            Console.WriteLine("Date and Time: {0}", date);
            Console.WriteLine("Month Value:   {0}\n", strDay);
            return 0;
        }
    }
}

This would display:

Date and Time: 4/2/2002 12:00:00 AM
Month Value:   02

Press any key to continue . . .
yy The double y is used to get the numeric year with the last two digits. Here is an example:
using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime date = new DateTime(2002, 4, 2);
            string strYear2Digits = date.ToString("yy");

            Console.WriteLine("Date and Time: {0}", date);
            Console.WriteLine("Year Value:    {0}\n", strYear2Digits);
            return 0;
        }
    }
}

This would produce:

Date and Time: 4/2/2002 12:00:00 AM
Year Value:    02

Press any key to continue . . .
yyyy The yyyy string is used to get all four digits of a year. Here is an example:
using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime date = new DateTime(2002, 4, 2);
            string strYear4Digits = date.ToString("yyyy");

            Console.WriteLine("Date and Time: {0}", date);
            Console.WriteLine("Year Value:    {0}\n", strYear4Digits);
            return 0;
        }
    }
}

This would produce:

Date and Time: 4/2/2002 12:00:00 AM
Year Value:    2002

Press any key to continue . . .

If the year was provided with two digits, such as 98, it would still be produced with 4 digits. Consider the following example:

using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime date = new DateTime(98, 4, 2);
            string strYear4Digits = date.ToString("yyyy");

            Console.WriteLine("Date and Time: {0}", date);
            Console.WriteLine("Year Value:    {0}\n", strYear4Digits);
            return 0;
        }
    }
}

This would produce:

Date and Time: 4/2/0098 12:00:00 AM
Year Value:    0098

Press any key to continue . . .

Notice that this may be a wrong date. For this reason, in your C# applications, you should always make it a habit to (always) provide your years with 4 digits.

Compilers  (as done in different implementations of various languages (C++, Pascal, Visual Basic, Java, SQL, Oracle, DB2, etc)), libraries (Win32, VCL, MFC, etc), applications (Microsoft Excel, OpenOffice.Org, Microsoft Access, Sun StarOffice, Quattro Pro, etc), and programming environments (Borland Developer Studio) have different ways of performing this operation. For example, in Microsoft Excel, if you are using the computer in the year 2006, if you provide a date value that has a year set with two digits such as 98, Microsoft Excel would add the two digits of the previous century, in this 19, to produce 1998. If you provide a year such as 02, the Microsoft Excel interpreter would add the current century to produce 2002.
 

Date Formats

 

The Computer’s System of Displaying Dates

To display a date in an application, by default, the compiler checks the Regional Options of the Control Panel. To see the options, from the Control Panel, you can double-click Regional or Language Option. From the Regional Options tab of the Regional or Language Option dialog box, you can click Customize... In the Customize Regional Options dialog box, click Date.

Getting a Date Value From a DateTime Object

You may have notice that, by default, a DateTime object always produces both a date and a time. In some cases, you will be interested in only the date portion of the object. To get a date value, you can call the DateTime.ToString() method that takes a String as argument and apply some rules:

Format Description
  Empty Space: Between the components of a date value, you are allowed to leave empty spaces if you want.
Don't pass an empty space to the ToString() method.
, Comma: To separate the sections of a date value, you can use the comma.
Don't pass a comma by itself to the ToString() method.
/ Date Separator: The compiler refers to the Control Panel to identify this character. In US English, the forward slash is used to separate the portions of a date:

Customize Regional Options

Don't pass the forward slash by itself to the ToString() method.

Others: - . Dash and Others: Besides the forward slash, the user's computer may allow other characters. For example, in US English, the "-" can be used. You can check available characters in the Date Separator combo box of the Date tab of the Customize Regional Options of the Control Panel.
Don't pass any of these characters by itself to the ToString() method.

The other characters and their combinations (MM, MMM, MMMM, dd, yy, and yyyy) are used as we reviewed them. 

Here are examples of displaying date formats:

using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime date = new DateTime(2004, 10, 23);

            Console.WriteLine("Date and Time:  {0}", date);
            Console.WriteLine(date.ToString("M/d/yyyy"));
            Console.WriteLine(date.ToString("M/d/yy"));
            Console.WriteLine(date.ToString("MM/dd/yy"));
            Console.WriteLine(date.ToString("MM/dd/yyyy"));
            Console.WriteLine(date.ToString("yy/MM/dd"));
            Console.WriteLine(date.ToString("yyyy-MM-dd"));
            Console.WriteLine(date.ToString("dd-MMM-yy"));
            return 0;
        }
    }
}

This would produce:

10/15/2006
10/15/06
10/15/06
10/15/2006
06/10/15
2006-10-15
15-Oct-06
Press any key to continue . . .

The Short Date

Instead of creating your own format, the Microsoft Windows operating system provides two names that can be used to identify a date. A date is referred to as short if it includes (only) the numeric portions of the month and the day of a date value. The operating systems follows the rules we have reviewed so far for the numbers and the Date Separator. The possible formats of a short date can be seen in the Short Date Format combo box of the Date tab of the Customize Regional Options of the Regional and Language Settings of the Control Panel:

Date Formats

To get the Short Date of a DateTime object, pass a "d" (one d in lowercase) string to the ToString() method. Here is an example:

using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime date = new DateTime(2004, 10, 23);
            string strDate = date.ToString("d");

            Console.WriteLine("Date and Time: {0}", date);
            Console.WriteLine("Date Portion:  {0}\n", strDate);
            return 0;
        }
    }
}

This would produce:

Date and Time: 10/23/2004 12:00:00 AM
Date Portion:  10/23/2004

Press any key to continue . . .

The Long Date Format

A date is referred to as long if it includes the names of the month and the day of the week of a date value. This is called the Long Date Format. To get the Long Date of a date, pass a "D" (one d in uppercase) string to the ToString() method of a DateTime object. Here is an example:

using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime date = new DateTime(2004, 10, 23);
            string strDate = date.ToString("D");

            Console.WriteLine("Date and Time: {0}", date);
            Console.WriteLine("Date Portion:  {0}\n", strDate);
            return 0;
        }
    }
}

To produce the result, the compiler refers to the Long Date Format combo box of the Customize Regional Options of the Control Panel. The user can change the format by selecting one from the combo box:

Date Regional

Based on the default settings of a computer used in US English, the above program would produce:

Date and Time: 10/23/2004 12:00:00 AM
Date Portion:  Saturday, October 23, 2004

Press any key to continue . . .

Other Date Formats

The .NET Framework provides other formats, not regularly used but available. To get the name of a month and the year value of a DateTime object, both separated by an empty space, pass a single M (uppercase) as string to the ToString() method of a DateTime object. Here is an example:

using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime date = new DateTime(2004, 10, 23);
            string strDate = date.ToString("M");

            Console.WriteLine("Date and Time:  {0}", date);
            Console.WriteLine("Month and Year: {0}\n", strDate);
            return 0;
        }
    }
}

This would produce:

Date and Time:  10/23/2004 12:00:00 AM
Month and Year: October 23

Press any key to continue . . .

To include a comma in the result, pass a single y (lowercase) as string to the ToString() method of a DateTime object. Here is an example:

using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime date = new DateTime(2004, 10, 23);
            string strDate = date.ToString("y");

            Console.WriteLine("Date and Time:  {0}", date);
            Console.WriteLine("Month and Year: {0}\n", strDate);
            return 0;
        }
    }
}

This would produce:

Date and Time:  10/23/2004 12:00:00 AM
Month and Year: October, 2004

Press any key to continue . . .
 

Operations on Dates

 

The Leap Year

One of the operations performed on date values is to find out whether the year value of a date is a leap year. Fortunately, the static IsLeapYear() method of the DateTime structure can be used to perform this operation. The syntax of this function is:

public static bool IsLeapYear(int year);

This method takes an integer argument and examines it. If the argument, which must be a valid year number, is a leap year, the method returns true; otherwise, it would return false. Here are two examples:

using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime date = new DateTime(1988, 10, 6);
            Console.WriteLine("{0} was a leap year: {1}",
                              date.Year, DateTime.IsLeapYear(date.Year));

            date = new DateTime(1990, 8, 12);
            Console.WriteLine("{0} was a leap year: {1}",
                              date.Year, DateTime.IsLeapYear(date.Year));

            return 0;
        }
    }
}

This would produce:

1988 was a leap year: True
1990 was a leap year: False
Press any key to continue . . .

The Day of the Week

The DateTime structure is equipped with a property that can be used to retrieve the day of the week for a given date. The property is named DayOfWeek. To get the day of the week, access the DayOfWeek property a your DateTime value or variable. The values are stored in the DayOfWeek enumeration. Here is an example:

using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime date = new DateTime(1988, 10, 6);

            Console.WriteLine("Day of the week: {0}", date.DayOfWeek);

            return 0;
        }
    }
}

This would produce:

Day of the week: Thursday
Press any key to continue . . .

A Time Span

Dates are some of the most important values of the operating system and many applications need them to perform their routine operations. Common operations include adding days to a date, subtracting months from a date, adding years, comparing dates to find out whether one occurs before another, finding out if a payroll falls on a holiday, etc. To perform some of these operations, a unit called an interval is considered as part of a date. A date interval is the number of days, months, or years that have elapsed, or would elapse, from one starting date to another ending date. Once you have specified this interval, you can then apply it to a date with the operation of your choice.

To support the ability to perform operations on dates, the .NET Framework is provides the TimeSpan structure. This structure is equipped with various members that would be applied on the TimeSpan structure. The value produced by this structure is then applied to a DateTime object. To create a date interval, declare a TimeSpan variable and initialize it with the desired value(s). To make this possible, the TimeSpan structure is equipped with various constructors.

Adding and/or Subtracting Days

With the DateTime structure, you can add some days to an existing date or subtract some days from a date value. To support this, the DateTime structure is equipped with the AddDays() method. Its syntax is:

public DateTime AddDays(int days);

Here is an example of calling this method:

using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime startDate = new DateTime(1988, 10, 6);
            Console.WriteLine("Starting Date: {0}", startDate);
            
            // This will be used to add 8 days to the previous date
            DateTime endDate = startDate.AddDays(8);
            // And display it
            Console.WriteLine("Ending Date:   {0}\n", endDate);

            return 0;
        }
    }
}

This would produce:

Starting Date: 10/6/1988 12:00:00 AM
Ending Date:   10/14/1988 12:00:00 AM

Press any key to continue . . .

If you pass a positive value to the DateTime.AddDays() method, a number of days is added to the DateTime variable. If you want to subtract some days from a date, pass the argument with a negative value. This method is able to figure out the year before, the month before, the day before, the day after, the month after, and the year after the designated date.

One of the constructors of the TimeSpan structure takes four arguments. Its syntax

public TimeSpan(int days, int hours, int minutes, int seconds);

The first argument of this constructor represents the number of days. If you are planning to add a number of days to a date, pass a positive integer as the first argument. If you want to subtract a date, pass a negative value. If you want to add only a number of days, pass only this argument.

After creating a TimeSpan object, you can call the Add() method of the DateTime structure to a date value. This would produce a new DateTime object that is the resulting value. Here are examples:

using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime startDate = new DateTime(1988, 10, 6);
            Console.WriteLine("Starting Date: {0}\n", startDate);
            
            // This will be used to add 172 days to the previous date
            TimeSpan ts = new TimeSpan(172, 0, 0, 0);
            // Pass the TimeSpan object to the date
            DateTime endDate = startDate.Add(ts);
            // And display it
            Console.WriteLine("Ending Date:   {0}\n", endDate);

            // Subtract 10 days to the previous date
            ts = new TimeSpan(-10, 0, 0, 0);
            // Pass the TimeSpan object to the date
            endDate = startDate.Add(ts);
            // And display it
            Console.WriteLine("Ending Date:   {0}\n", endDate);

            return 0;
        }
    }
}

This would produce:

Starting Date: 10/6/1988 12:00:00 AM

Ending Date:   3/27/1989 12:00:00 AM

Ending Date:   9/26/1988 12:00:00 AM

Press any key to continue . . .

Notice that, when adding or subtracting days, the complier can figure out the previous day, the previous month, the previous year, the following day, the following month, or the following year.

Adding or Subtracting Months to a Date

To add a number of months to a date, the DateTime class is equipped with a method named AddMonths(). Its syntax is:

public DateTime AddMonths(int months);

This method takes one argument as the number of months to be added or subtracted. If you pass the argument with a positive value, the months are added to the date. If you pass a negative value, the number of months is subtracted from the date.

Adding or Subtracting Years to a Date

To get the date a few years before or after a known date, you can add years to, or subtract years from, a known date. To support this operation, the DateTime class provides a method named AddYears(). Its syntax is:

public DateTime AddYears(int years);

The argument passed to the method is the number of years. A positive value (or a negative value) adds (or subtracts) the number of years to (or from) the date.

Logical Operations on Dates

Using the logical operators we reviewed for primitive types, you can compare the values of dates for equality, differences, lower or greater values. To support these operations, the DateTime structure have the logical operators configured.

To compare two dates, apply the desired Boolean operator the same day you would two variables of primitive types. Here is an example:

using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime startDate = new DateTime(1988, 10, 6);
            Console.WriteLine("Starting Date: {0}", startDate);
            
            // This will be used to add 8 days to the previous date
            DateTime endDate = startDate.AddDays(8);
            // And display it
            Console.WriteLine("Ending Date:   {0}\n", endDate);

            if (startDate < endDate)
                Console.WriteLine("{0} Occurs Before {1}", startDate, endDate);

            return 0;
        }
    }
}

This would produce:

Starting Date: 10/6/1988 12:00:00 AM

Ending Date:   10/14/1988 12:00:00 AM

10/6/1988 12:00:00 AM Occurs Before 10/14/1988 12:00:00 AM
Press any key to continue . . .

Time

 

Introduction

As defined earlier, the time is a value used to identify the number of units that have elapsed since a starting period, called midnight, of a day. A day is made of 24 non-spatial divisions; each one of these divisions is called an hour. An hour is made of 60 fractions and each one of these fractions is called a minute. A minute is divided in 60 parts, each called a second. As done with dates, most of the operations performed on time values are centered around the DateTime structure.

The rules used by the computer for time display can be seen in the Customize Regional Options dialog box. To access it, in the Control Panel, you can double-click Regional and Language Options. In the Regional Options tab of the Regional and Language Options dialog box, you can click Customize. In the Customize Regional Options, you can click Time:

Customize Regional Options

In US English, the symbol to separate the hour and the minute. An example would be: 08:25. In the same way, in US English, the character used to separate the minute and the second is “:”. An example would be: 08:25:44. In many cases, unless necessary, the second is not represented in a time value.

The time of a day can be considered as a value of 24 hours or the day can be considered as two fractions of 12 hours each. There is a period in the middle of day time called noon. It divides the 24-hour day in two parts, each consisting of 12 hours. The noon period is positioned 12 hours after midnight. The period that goes from midnight to the middle of day time is represented by the expression AM. The period from noon to midnight is represented by the PM expression. When a DateTime object includes an AM or PM but of unknown value, the section is represented as AM/PM and this expression is written on the right side of the seconds. To separate the seconds and the AM/PM, you (as well as the compiler) leave a one-character empty space after the seconds.

Creating a Time Value

The time portion of a DateTime structure can be declared and manipulated as a value. To create a time value, you can declare a DateTime variable using the following constructor:

public DateTime(int year, int month, int day,
		int hour, int minute, int second);

If you are more concerned about the time, the first, second, and third arguments are not important. You can pass each as 1. In this case, the date would be set as January 1, 0001. The other three arguments represent the components of a time value.

The minutes value must range from 0 to 59; otherwise, an error would be produced (when studying exception handling, we will see that this means that the compiler would throw an exception). The seconds value must be between 0 and 59 or the program would cause an error.

When initializing a date or time variable using this constructor, the hour value must be between 0 and 23. Any other value outside of this range will cause an error. If the hour portion has a value between 0 and 11, the time is set in the morning with the AM in the AM/PM section. Here is an example:

using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime time = new DateTime(1, 1, 1, 10, 24, 52);

            Console.WriteLine("Time: {0}\n", time);
            return 0;
        }
    }
}

This would produce:

Time: 1/1/0001 10:24:52 AM

Press any key to continue . . .

If the hour portion is between 12 and 23, the time is set in the afternoon. When displaying it, the compiler, by default, calculates and displays the 0 to 12 portion and then displays PM in the AM/PM section. Here is an example:

using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime time = new DateTime(1, 1, 1, 16, 8, 44);

            Console.WriteLine("Time: {0}\n", time);
            return 0;
        }
    }
}

This would produce:

Time: 1/1/0001 4:08:44 PM

Press any key to continue . . .

In extreme cases, you may want to use the milliseconds of a time value. When declaring and initializing the variable, you can use the following constructor:

public DateTime(int year, int month, int day,
		int hour, int minute, int second, int millisecond);

The milliseconds must range from 0 to 999. If you do not know the millisecond value, you can provide it as 0.

Retrieving a Time Value

In a certain application, you may want the user to supply a time value. As mentioned for the date, there are rules that you, the computer, and the user must follow to apply a valid formula. As mentioned earlier, the compiler refers to the computer to find out what a date looks like. A valid time can follow the format hh:nn AM/PM or hh:nn:ss or one of the valid combinations. When requesting a time from  the user, in case the user is not familiar with the rules (and you should assume that the user doesn't know them), specify what formula the user should follow. Here is an example:

using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime dateSubmitted;
            
            Console.Write("Enter a date (yyyy/mm/dd): ");
            dateSubmitted = DateTime.Parse(Console.ReadLine());

            Console.WriteLine("\nDate Submitted: {0}\n", dateSubmitted);
            return 0;
        }
    }
}

Here is an example of running the program: 

Enter a date (yyyy/mm/dd): 1996/08/16

Date Submitted: 8/16/1996 12:00:00 AM

Press any key to continue . . .

The Characteristics of a Time Value

 

The Components of a Time

By now, we have seen that a time value is made of the hour, the minute, the second, and the millisecond parts. These are values you can specify when creating a time object using one of the appropriate constructors of the DateTime structure. If you request a time value from the user or if the application itself will provide it, you can retrieve its components.

To get the hour portion of an existing DateTime object, you can access its Hour property. To retrieve the minute side of a time value, access its Minute property. If you want to know the second value of a DateTime variable, you can call its Second property. In the same way, you can get the millisecond value of a time by accessing its Millisecond property.

The Time of Day of a DateTime Value

As seen so far, a DateTime variable always holds both a date and a time portions. In your program, you may want to get only the time of the variable. To support this, the DateTime structure is equipped with a property named TimeOfDay. This property produces the time value of an existing DateTime object. Here is an example of using it:

using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime time = new DateTime(2002, 4, 22, 16, 8, 44);

            Console.WriteLine("Date and Time: {0}\n", time);
            Console.WriteLine("Time of Day:   {0}\n", time.TimeOfDay);
            return 0;
        }
    }
}

This would produce:

Date and Time: 4/22/2002 4:08:44 PM

Time of Day:   16:08:44

Press any key to continue . . .

Operations on Time Values

 

Converting a Time Value to a String

If you have a DateTime object, you can convert it to a String value. To make this operation possible, the DateTime structure is equipped with a method named ToString. The default version of this method takes no argument and it simply creates a string out of a time value. Here is an example:

using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime time = new DateTime(2002, 4, 22, 16, 8, 44);
            string strTime = time.ToString();

            Console.WriteLine("Date and Time(DateTime): {0}\n", time);
            Console.WriteLine("Date and Time(String):   {0}\n", strTime);
            return 0;
        }
    }
}

This would produce:

Date and Time(DateTime): 4/22/2002 4:08:44 PM

Date and Time(String):   4/22/2002 4:08:44 PM

Press any key to continue . . .

Notice that the value produced by the string includes both the date, the time and even the AM/PM section. In some cases, you would be interested only in either the date or the time. To support this type of operation, the DateTime structure has another overloaded version of the ToString() method that takes as argument a String value. Its syntax is:

public string ToString(string format);

When calling this method, there are rules you should/must follow.

Time Rules and Formats

Like dates, time values follow the Regional (and Language) Settings of Control Panel when they display. To make this display friendlier, Microsoft Windows provides the rules, through some characters, you can use to format a time:

Time

 The characters used to create a format are:

Format Used For Description
hh Hours An hour number from 0 to 23.
If the hour is less than 10, it would display with the leading 0 such as 08. Here is an example:
using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime time = new DateTime(2002, 4, 22, 5, 8, 37);
            string strHour = time.ToString("hh");

            Console.WriteLine("Date and Time: {0}", time);
            Console.WriteLine("Hour Value:    {0}\n", strHour);
            return 0;
        }
    }
}
This would produce:
Date and Time: 4/22/2002 5:08:37 AM
Hour Value:    05

Press any key to continue . . .

If the hour is greater than 12, such as 15, 12 would be subtract from it and it would display with a leading 0, such as 05. Here is an example:

using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime time = new DateTime(2002, 4, 22, 15, 8, 37);
            string strHour = time.ToString("hh");

            Console.WriteLine("Date and Time: {0}", time);
            Console.WriteLine("Hour Value:    {0}\n", strHour);
            return 0;
        }
    }
}
This would produce:
Date and Time: 4/22/2002 5:08:37 AM
Hour Value:    05

Press any key to continue . . .
HH Hours An hour number from 0 to 23.
If the hour is less than 10, it would display with the leading 0 such as 08. The effect is the same as seen for the hh format.
If the hour is greater than 12, such as 15, it would display with that value. Here is an example:
using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime time = new DateTime(2002, 4, 22, 15, 8, 37);
            string strHour = time.ToString("HH");

            Console.WriteLine("Date and Time: {0}", time);
            Console.WriteLine("Hour Value:    {0}\n", strHour);
            return 0;
        }
    }
}
This would produce:
Date and Time: 4/22/2002 3:08:37 PM
Hour Value:    15

Press any key to continue . . .
mm Minutes A minute number from 0 to 59.
If the number is less than 10, it would display with the leading 0 such as 06. Here is an example:
using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime time = new DateTime(2002, 4, 22, 15, 8, 37);
            string strMinute = time.ToString("mm");

            Console.WriteLine("Date and Time: {0}", time);
            Console.WriteLine("Minute Value:    {0}\n", strMinute);
            return 0;
        }
    }
}

This would produce:

Date and Time: 4/22/2002 3:08:37 PM
Minute Value:    08

Press any key to continue . . .

If the number is greater than 9, it would display the same.

ss Seconds A second value from 0 to 59.
If the number is less than 10, it would display with the leading 0 such as 04. Here is an example:
using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime time = new DateTime(2002, 4, 22, 15, 8, 7);
            string strSecond = time.ToString("ss");

            Console.WriteLine("Date and Time: {0}", time);
            Console.WriteLine("Hour Value:    {0}\n", strSecond);
            return 0;
        }
    }
}
This would produce:
Date and Time: 4/22/2002 3:08:07 PM
Hour Value:    07

Press any key to continue . . .

If the number is greater than 9, it would display like that. 

tt
or
tttt
AM/PM Expression used to produce the AM or PM side of a time value. Here is an example:
using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime time = new DateTime(2002, 4, 22, 5, 8, 7);
            string strAMPM = time.ToString("tt");

            Console.WriteLine("Date and Time: {0}", time);
            Console.WriteLine("AM/PM Side:    {0}\n", strAMPM);
            return 0;
        }
    }
}

This would produce:

Date and Time: 4/22/2002 5:08:07 AM
AM/PM Side:    AM

Press any key to continue . . .

To create or format a (complete) time value, you must use a combination of characters:

Format Used For Description
: Separator The character separator for time values.
This character is set in the Regional (and Language) Settings of Control Panel.
Don't use this character by itself in a ToString() method.
h or H Hours An hour number from 0 to 23.
If the hour is less than 10, it would display without the leading 0.
Don't use the letter "h" or "H" by itself in a ToString() method
m Minutes A minute number from 0 to 59.
If the number is less than 10, it would display without the leading 0. Here is an example:
using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime time = new DateTime(2002, 4, 22, 15, 8, 37);
            string strMinute = time.ToString("h:m");

            Console.WriteLine("Date and Time: {0}", time);
            Console.WriteLine("Minute Value:    {0}\n", strMinute);
            return 0;
        }
    }
}

This would produce:

Date and Time: 4/22/2002 3:08:37 PM
Minute Value:    3:8

Press any key to continue . . .

If the minute number is greater than 9, it would display as such.
Don't use the letter "m" by itself in a ToString() method.

mm Minutes A minute number from 0 to 59.
If the number is less than 10, it would display with a leading 0. Here is an example:
using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime time = new DateTime(2002, 4, 22, 15, 8, 37);
            string strMinute = time.ToString("h:mm");

            Console.WriteLine("Date and Time: {0}", time);
            Console.WriteLine("Minute Value:    {0}\n", strMinute);
            return 0;
        }
    }
}

This would produce:

Date and Time: 4/22/2002 3:08:37 PM
Minute Value:    3:08

Press any key to continue . . .

Don't pass "mm" by itself in a ToString() method

s Seconds A second value from 0 to 59.
If the number is less than 10, it would display without a leading 0. Here is an example:
using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime time = new DateTime(2002, 4, 22, 15, 8, 7);
            string strSecond = time.ToString("h:mm:s");

            Console.WriteLine("Date and Time: {0}", time);
            Console.WriteLine("Second Value:    {0}\n", strSecond);
            return 0;
        }
    }
}

This would produce:

Date and Time: 4/22/2002 3:08:07 PM
Minute Value:    3:08:7

Press any key to continue . . .

Don't pass "mm" by itself in a ToString() method

ss Seconds A second value from 0 to 59.
If the number is less than 10, it would display with a leading 0. Here is an example:
using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            DateTime time = new DateTime(2002, 4, 22, 15, 8, 7);
            string strSecond = time.ToString("h:mm:ss");

            Console.WriteLine("Date and Time: {0}", time);
            Console.WriteLine("Second Value:    {0}\n", strSecond);
            return 0;
        }
    }
}

This would produce:

Date and Time: 4/22/2002 3:08:07 PM
Minute Value:    3:08:07

Press any key to continue . . .

Don't pass "mm" by itself in a ToString() method

When combining these characters to create a format, you should abide by the rules of your language, such as US English. You should refer to the formula set in the Time property page of the Regional (and Language) Settings of Control Panel.

Comparison Operations On Time Values

As done for date values, you can compare time values to find out if one occurs before another or whether they occur at the same time. To support the comparisons, the DateTime structure is equipped with the Compare() method.

Combining Date and Time

 

The Current Date and Time

When a user starts a computer and while using it, it keeps a date and time values referred to as local date and time or system date and time. Depending on your application, at one time you may need to get one or both of these pieces of information. It is important to know that the computer, not you, controls this information (but you can programmatically change it if you want). To support both, the DateTime structure is equipped with a static property named Now. This property holds the year, the month, the day, the name of the day, the hour, the minute, and the second. Here is an example of calling it:

using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            Console.WriteLine("System Date and Time: {0}", DateTime.Now);
            return 0;
        }
    }
}

Here is an example of running the program:

System Date and Time: 10/15/2006 3:08:48 PM
Press any key to continue . . .

To get the current date of the computer, the DateTime structure provides a static property named Today. Here is an example:

using System;

namespace DateAndTime
{
    class Program
    {
        static int Main()
        {
            Console.WriteLine("Current Date: {0}", DateTime.Today);
            return 0;
        }
    }
}

Here is an example of running the program:

Current Date: 10/15/2006 12:00:00 AM
Press any key to continue . . .
 

Formatting Date and Time Combinations

Although the DateTime structure is equipped to produce default values of a date and time in combination, you can use the formats we have reviewed to create your own date, in the sequences of your choice, such as a time preceding a date, a value providing only the month and the minutes, etc.


Previous Copyright © 2008-2016, FunctionX, Inc. Next