Dates Fundamentals

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. 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 group of units between two midnight points is called a day. The days are counted from 1, 2, 3, and so on.

Practical LearningPractical Learning: Introducing Date Values

  1. Start Microsoft Visual Studio
  2. To create a new application, on the main menu, click File -> New -> Project...
  3. In the middle list, click Console App (.NET Framework)
  4. Set the name to GeorgetownDryCleaningServices5
  5. Click OK

Date Value Creation

To represent the dates, computers, applications, and compilers are configured with specific techniques. In Microsoft Windows, to manage dates, the operating system in its Win32 library provides a structure named SYSTEMTIME. To manage dates, the .NET Framework provides a structure named DateTime. To create a date value, you can first declare a 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
{
    public class Exercise
    {
        public 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.

Primary Characteristics of a Date

The Day of a Date Value

A day is the period from one midnight to the next midnight (or just before midnight). To make it easy to identify a day, the days in US English are named Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, and Sunday. To support the day, the DateTime structure is equipped with a read-only property named DayOfWeek. The value of this property is from en enumeration of the same name:

public DayOfWeek DayOfWeek { get; }

The members of the DayOfWeekenumeration are Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, and Sunday. Use the DateTime.DayOfWeek property to get the name of a day of a date value. Here is an example:

using System;

namespace DateAndTime
{
    public class Exercise
    {
        public static void Main()
        {
            DateTime infractionDate = new DateTime();

            Console.WriteLine("Day: " + infractionDate.DayOfWeek);

            Console.WriteLine("=============================");

            return;
        }
    }
}

This would produce:

Day: Monday
=============================
Press any key to continue . . .

A Week

A week is a group of seven consecutive days.

A Month

By essence, a month is a group of four consecutive weeks. To support the month, the DateTime structure is equipped with a read-only integer property named Month:

public int Month { get; }

The integer type represents the position of the month within the year if the date. The months are counted from 1 and up. To make it easy to identify a month, each month holds a name, long or short. In US English, the long names of months are January, February, March, April, May, June, July, August, September, October, November, and December. The short names of months in US English are Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, and Dec.

A Year

A year is a group of 12 consecutive months. To support the year value, the DateTime structure is equipped with a numeric property named Year:

public int Year { get; }

The Day of a Year

A year is a series of days, 360, 365, or 366, depending on some factors. The days are numbered as 1, 2, 3, and so on. To support the days of a year, the DateTime structure is equipped with a numeric property named Day:

public int Day { get; }

Date Creation

To create a date value, you should (must) provide the year, the month in that year, and the day in that month. To support this way of creating a date, A date is a technique of identifying a period using three numbers: the year, the month, and the day. To support this way of creating a date value, the DateTime structure is equipped with the following constructor:

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

The value of a year is a number between 1 and 9999. The value of the month must be between 1 and 12. The values of the day are as follows:

Month Days Between 1 and
Jan or January 31
Mar or March 31
Apr or April 30
May 31
Jun or June 30
Jul or July 31
Aug or August 31
Sep or September 30
Oct or October 31
Nov or November 30
Dec or December 31

Depending on a factor named Leap Year, the month of Feb or February can have days between 1 and 28 or 1 and 29. When February has 28 days, the year has 365 days, otherwise it has 366 days. Here is an example of creating a date:

using System;

namespace DateAndTime
{
    public class Exercise
    {
        public static int Main()
        {
            DateTime ind = new DateTime(1960, 1, 1);
            
            return 0;
        }
    }
}

To display a date value, you can pass it to the Console.Write() or the Console.WriteLine() method. Here is an example:

using System;

namespace DateAndTime
{
    public class Program
    {
        public 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 . . .

We already saw how to get the day, the month, and the year of a date value. Once you have a date value, the name of the day of that date is represented by the DateTime.DayOfWeek property. Here is an example:

using System;

namespace DateAndTime
{
    public class Membership
    {
        public static void Main()
        {
            DateTime independence = new DateTime(1962, 7, 5);

            Console.Write("Independence Day: " + independence.DayOfWeek);
            Console.WriteLine(" " + independence);

            Console.WriteLine("=============================");

            return;
        }
    }
}

This would produce:

Independence Day: Thursday 7/5/1962 12:00:00 AM
=============================
Press any key to continue . . .

The Default Date Value

The default constructor of the DateTime structure initializes the date to January 1st, 0001 and the time at midnight. 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.

Requesting a Date Value

As done with the regular numbers, you can request a date value from the user. This is also done by requesting a string from the user. Here is an example:

using System;

namespace ValueRequests
{
    class Exercise
    {
		static void Main()
		{
		    string strDateHired;

	    	strDateHired = Console.ReadLine();
		}
    }
}

After the user has entered the string, you can convert it to a DateTime value. Just like any value you request from the user, a date or time value that the user types must be valid, otherwise, the program would produce an error. Because dates and times follow some rules for their formats, you should strive to let the user know how you expect the value to be entered.

By default, if you request only a date from the user and the user enters a valid date, the compiler would add the midnight value to the date. If you request only the time from the user and the user enters a valid time, the compiler would add the current date to the value.

Practical LearningPractical Learning: Requesting a Date Value

  1. In the Solution Explorer, right-click Program.cs -> Rename
  2. Type GeorgetownDryCleaningServices to get GeorgetownDryCleaningServices, and press Enter
  3. Read the text on the message box and click Yes
  4. Change the document as follows:
    using System;
    
    namespace GeorgetownDryCleaningServices
    {
        class GeorgetownDryCleaningServices
        {
            public static int Main(string[] args)
            {
                // Price of items
                const double PriceOneShirt = 1.25;
                const double PriceAPairOfPants = 2.15;
                const double PriceOtherItem = 3.45;
                const double TaxRate = 5.75;  // 5.75%
    
                // Basic information about an order
                string customerName, homePhone;
                DateTime orderDate = new DateTime();
                // Unsigned numbers to represent cleaning items
                ushort numberOfShirts = 0, numberOfPants = 0, numberOfOtherItems = 0;
                // Each of these sub totals will be used for cleaning items
                double subTotalShirts, subTotalPants, subTotalOtherItems;
                // Values used to process an order
                double totalOrder, taxAmount, salesTotal;
                double amountTended = 0, moneyChange;
    
                Console.Title = "Georgetown Dry Cleaning Services";
    
                Console.WriteLine("===============================================");
                Console.WriteLine("-/-    Georgetown Dry Cleaning Services    -/-");
                Console.WriteLine("==============================================");
                // Request order information from the user
                Console.Write("Enter Customer Name:                ");
                customerName = Console.ReadLine();
                Console.Write("Enter Customer Phone:               ");
                homePhone = Console.ReadLine();
                Console.Write("Enter the order date (mm/dd/yyyy):  ");
                try
                {
                    orderDate = DateTime.Parse(Console.ReadLine());
                }
                catch(FormatException fexc)
                {
                    Console.BackgroundColor = ConsoleColor.DarkBlue;
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine(fexc.Message);
                }
    
                Console.ResetColor();
    
                // Request the quantity of each category of items
                try
                {
                    Console.Write("Number of Shirts:                   ");
                    numberOfShirts = ushort.Parse(Console.ReadLine());
                }
                catch(FormatException)
                {
                    Console.WriteLine("The value you typed for the number of " +
                              "shirts is not a valid number.");
                }
    
                try
                {
                    Console.Write("Number of Pants:                    ");
                    numberOfPants = ushort.Parse(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("The value you typed for the number of " +
                              "pants is not a valid number.");
                }
    
                try
                {
                    Console.Write("Number of Other Items:              ");
                    numberOfOtherItems = ushort.Parse(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("The value you typed for the number of " +
                              "other types of items is not a valid number.");
                }
    
                // Perform the necessary calculations
                subTotalShirts = numberOfShirts * PriceOneShirt;
                subTotalPants = numberOfPants * PriceAPairOfPants;
                subTotalOtherItems = numberOfOtherItems * PriceOtherItem;
                // Calculate the "temporary" total of the order
                totalOrder = subTotalShirts + subTotalPants + subTotalOtherItems;
    
                // Calculate the tax amount using a constant rate
                taxAmount = totalOrder * TaxRate / 100.00;
                // Add the tax amount to the total order
                salesTotal = totalOrder + taxAmount;
    
                Console.WriteLine("-----------------------------------------");
                // Communicate the total to the user...
                Console.WriteLine("The Total order is:                 {0:C}", salesTotal);
                // and request money for the order
                try
                {
                    Console.Write("Amount Tended?                      ");
                    amountTended = double.Parse(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("You were asked to enter an amount of money but something bad happened.");
                }
    
                // Calculate the difference owed to the customer
                // or that the customer still owes to the store
                moneyChange = amountTended - salesTotal;
    
                Console.Clear();
                Console.Title = "Georgetown Dry Cleaning Services";
    
                // Display the receipt
                Console.WriteLine("=========================================");
                Console.WriteLine("-/- Georgetown Dry Cleaning Services -/-");
                Console.WriteLine("=========================================");
                Console.WriteLine("Customer:   {0}", customerName);
                Console.WriteLine("Home Phone: {0}", homePhone);
                Console.WriteLine("Order Date: {0}", orderDate);
                Console.WriteLine("-----------------------------------------");
                Console.WriteLine("Item Type    Qty Unit/Price Sub-Total");
                Console.WriteLine("-----------------------------------------");
                Console.WriteLine("Shirts{0,9}     {1:C}     {2:C}",
                          numberOfShirts, PriceOneShirt, subTotalShirts);
                Console.WriteLine("Pants{0,10}     {1:C}     {2:C}",
                          numberOfPants, PriceAPairOfPants, subTotalPants);
                Console.WriteLine("Other Items{0,4}     {1:C}     {2:C}",
                          numberOfOtherItems, PriceOtherItem, subTotalOtherItems);
                Console.WriteLine("-----------------------------------------");
                Console.WriteLine("Total Order:     {0:C}", totalOrder);
                Console.WriteLine("Tax Rate:        {0:P}", TaxRate / 100);
                Console.WriteLine("Tax Amount:      {0:C}", taxAmount);
                Console.WriteLine("Net Price:       {0:C}", salesTotal);
                Console.WriteLine("-----------------------------------------");
                Console.WriteLine("Amount Tended:   {0:C}", amountTended);
                Console.WriteLine("Difference:      {0:C}", moneyChange);
                Console.WriteLine("=========================================");
    
                return 0;
            }
        }
    }
  5. To execute the program, on the main menu, click Debutg -> Start Without Debugging:
    ===============================================
    -/-    Georgetown Dry Cleaning Services    -/-
    ==============================================
    Enter Customer Name:
  6. Type some values as follows:
    ===============================================
    -/-    Georgetown Dry Cleaning Services    -/-
    ==============================================
    Enter Customer Name:                Catherine Richarson
    Enter Customer Phone:               (202) 184-9738
    Enter the order date (mm/dd/yyyy):  27 Mais 2019
    The string was not recognized as a valid DateTime. There is an unknown word star
    ting at index 3.
    Number of Shirts:                   8
    Number of Pants:                    12
    Number of Other Items:              14
    -----------------------------------------
    The Total order is:                 $88.94
    Amount Tended?                      90
  7. Press Enter:
    =========================================
    -/- Georgetown Dry Cleaning Services -/-
    =========================================
    Customer:   Catherine Richarson
    Home Phone: (202) 184-9738
    Order Date: 1/1/1900 12:00:00 AM
    -----------------------------------------
    Item Type    Qty Unit/Price Sub-Total
    -----------------------------------------
    Shirts        8     $1.25     $10.00
    Pants        12     $2.15     $25.80
    Other Items  14     $3.45     $48.30
    -----------------------------------------
    Total Order:     $84.10
    Tax Rate:        5.75 %
    Tax Amount:      $4.84
    Net Price:       $88.94
    -----------------------------------------
    Amount Tended:   $90.00
    Difference:      $1.06
    =========================================
    Press any key to continue . . .
  8. Press Enter to close the window and return to your programming environment
  9. To create a new application, on the main menu, click File -> New -> Project...
  10. In the middle list, click Console App (.NET Framework)
  11. Change the Name to CountriesStatistics5
  12. Click OK
  13. In the Solution Explorer, right-click CountriesStatistics5 -> Add -> Class...
  14. Type Region as the Name of the class
  15. Click Add
  16. Change the document as follows:
    namespace CountriesStatistics4
    {
        public class Region
        {
            public string Designation { get; set; }
            public string Description { get; set; }
        }
    }
  17. In the Solution Explorer, right-click CountriesStatistics4 -> Add -> New Item...
  18. In the left frame of the Add New Item dialog box, click Code and, in the middle frame, click Interface
  19. Change the Name to Abbreviated
  20. Click Add
  21. Create a string-based property as follows:
    namespace CountriesStatistics4
    {
        interface IAbbreviated
        {
            string Abbreviation { get; set; }
        }
    }
  22. In the Solution Explorer, right-click CountriesStatistics4 -> Add -> New Item
  23. In the middle list of the dialog box, make sure Interface is selectd. Change the Name to GovernmentEntity
  24. Click Add
  25. Change the class as follows:
    namespace CountriesStatistics4
    {
        interface IGovernmentEntity
        {
            string Name    { get; set; }
            uint    Area    { get;      }
            string Capital { get; set; }
        }
    }
  26. In the Solution Explorer, right-click CountriesStatistics4 -> Add -> Class...
  27. Type State as the name of the file
  28. Press Enter
  29. Change the class as follows:
    using System;
    
    namespace CountriesStatistics4
    {
        public class State : IAbbreviated,
                             IGovernmentEntity,
                             IComparable
        {
            // From the IAbbreviated interface
            public string Abbreviation { get; set; }
            // From the IGovernmentEntity interface
            public string Name    { get; set; }
            public uint Area       { get; set; }
            public string Capital { get; set; }
    
            // New Properties
            public string StateName => Name;
            public uint AreaSqrMiles => Area;
            public uint AreaSqrKms   { get; set; }
            public Region Region    { get; set; }
    
            public int CompareTo(object stt)
            {
                if (stt == null)
                {
                    return 0;
                }
    
                State other = stt as State;
    
                if (other != null)
                    return StateName.CompareTo(other.StateName);
    
                return 0;
            }
        }
    }
  30. In the Solution Explorer, right-click CountriesStatistics4 -> Add -> Class...
  31. Type Federation
  32. Click Add
  33. Change the class as follows:
    using System;
    
    namespace CountriesStatistics4
    {
        public class Federation : State
        {
            public DateTime AdmissionUnionDate  { get; set; }
            public uint     AdmissionUnionOrder { get; set; }
        }
    }
  34. In the Solution Explorer, right-click Program.cs and click Rename
  35. Type CountriesStatistics to get CountriesStatistics.cs
  36. Read the message box and click Yes
  37. In the Solution Explorer, double-click CountriesStatistics.cs to access it
  38. Change the document as follows:
    using System;
    
    namespace CountriesStatistics4
    {
        public class CountriesStatistics
        {
            private static void Display(Array entities)
            {
                Console.Clear();
    
                Console.WriteLine("                                 United States of America");
                Console.WriteLine("=========================================================================================================");
                Console.WriteLine("                                 Area      Admission to Union");
                Console.WriteLine(" # Abbrv State Name        SqrMls     Km2   Date    Order         Capital         Region");
                Console.WriteLine("---------------------------------------------------------------------------------------------------------");
    
                for (int counter = 0; counter <= entities.Length - 1; counter++)
                {
                    Federation stt = (Federation)entities.GetValue(counter);
    
                    Console.WriteLine("{0,2}  {1,2}   {2}   {3,6}   {4,8}    {5,10}     {6}        {7}",
                                      counter + 1, stt.Abbreviation, stt.StateName,
                                      stt.AreaSqrMiles, stt.AreaSqrKms, stt.AdmissionUnionDate,
                                      stt.AdmissionUnionOrder, stt.Capital, stt.Region.Designation);
                }
                Console.WriteLine("=========================================================================================================");
            }
    
            public static int Main(string[] args)
            {
                Region[] regions = new Region[]
                   {
                    new Region() { Designation = "East North Central", Description = "The East North Central region includes the states around the Great Lakes." },
                    new Region() { Designation = "East South Central", Description = "The East South Central portion is one of the regions designated as the South." },
                    new Region() { Designation = "New England       ", Description = "New England is the group of states in the North-East region. It is delimited in the North and North-East by Canada, in the East by the Atlantic Ocean, and in the South and West by the New York state." },
                    new Region() { Designation = "Mid-Atlantic      ", Description = "Mid-Atlantic is a region situated in the south of New England. Mid-Atlantic is one of the regions defined by the Census bureau for statistical purposes." },
                    new Region() { Designation = "Mountain          ", Description = "Like the name suggests, the Mountain region covers states known for their mountaneous characteristics. They are also covered by desertic areas." },
                    new Region() { Designation = "Pacific           ", Description = "The Pacific region covers the costal western states plus the two non-continental states of Alaska and the Hawaiian islands. All states in this region have a coast on the Pacific Ocean." },
                    new Region() { Designation = "South Atlantic    ", Description = "The South Atlantic region includes the states in the South-East part but also counts the Disctrict of Columbia." },
                    new Region() { Designation = "West North Central", Description = "The West North Central region includes the states in the Great Planes area. This reqion is divided from the East North Central part by the Mississippi River. This region is characterized by vast agricultural farms and high employment." },
                    new Region() { Designation = "West South Central", Description = "The West South Central part is one of the regions with (only) four states. The imposing Texas state is both the largest and the most populous state in the region." }
                   };
    
                Federation[] states = new Federation[40];
    
                states[0]  = new Federation() { Abbreviation = "RI", Name = "Rhode Island  ", Area =    1545, AreaSqrKms =      4002, AdmissionUnionDate = new DateTime(1790, 05, 29), AdmissionUnionOrder = 13, Capital = "Providence    ", Region = regions[2] };
                states[1]  = new Federation() { Abbreviation = "OH", Name = "Ohio          ", Area =  44_828, AreaSqrKms =   116_103, AdmissionUnionDate = new DateTime(1803, 03, 01), AdmissionUnionOrder = 17, Capital = "Columbus      ", Region = regions[0] };
                states[2]  = new Federation() { Abbreviation = "KY", Name = "Kentucky      ", Area =  40_411, AreaSqrKms =   104_665, AdmissionUnionDate = new DateTime(1792, 06, 01), AdmissionUnionOrder = 15, Capital = "Frankfort     ", Region = regions[2] };
                states[3]  = new Federation() { Abbreviation = "IA", Name = "Iowa          ", Area =  56_276, AreaSqrKms =   145_754, AdmissionUnionDate = new DateTime(1846, 12, 28), AdmissionUnionOrder = 29, Capital = "Des Moines    ", Region = regions[7] };
                states[4]  = new Federation() { Abbreviation = "WI", Name = "Wisconsin     ", Area =  65_503, AreaSqrKms =   169_653, AdmissionUnionDate = new DateTime(1848, 05, 29), AdmissionUnionOrder = 30, Capital = "Madison       ", Region = regions[0] };
                states[5]  = new Federation() { Abbreviation = "VT", Name = "Vermont       ", Area =    9615, AreaSqrKms =    24_903, AdmissionUnionDate = new DateTime(1791, 03, 04), AdmissionUnionOrder = 14, Capital = "Montpelier    ", Region = regions[2] };
                states[6]  = new Federation() { Abbreviation = "ID", Name = "Idaho         ", Area =  83_574, AreaSqrKms =   216_456, AdmissionUnionDate = new DateTime(1890, 07, 03), AdmissionUnionOrder = 43, Capital = "Boise         ", Region = regions[4] };
                states[7]  = new Federation() { Abbreviation = "ME", Name = "Maine         ", Area =  35_387, AreaSqrKms =    91_653, AdmissionUnionDate = new DateTime(1820, 03, 15), AdmissionUnionOrder = 23, Capital = "Augusta       ", Region = regions[2] };
                states[8]  = new Federation() { Abbreviation = "OR", Name = "Oregon        ", Area =  98_386, AreaSqrKms =   254_819, AdmissionUnionDate = new DateTime(1859, 02, 14), AdmissionUnionOrder = 33, Capital = "Salem         ", Region = regions[5] };
                states[9]  = new Federation() { Abbreviation = "ND", Name = "North Dakota  ", Area =  70_704, AreaSqrKms =   183_123, AdmissionUnionDate = new DateTime(1889, 11, 02), AdmissionUnionOrder = 39, Capital = "Bismarck      ", Region = regions[7] };
                states[10] = new Federation() { Abbreviation = "IN", Name = "Indiana       ", Area =  36_420, AreaSqrKms =    94_328, AdmissionUnionDate = new DateTime(1816, 12, 11), AdmissionUnionOrder = 19, Capital = "Indianapolis  ", Region = regions[0] };
                states[11] = new Federation() { Abbreviation = "MS", Name = "Mississippi   ", Area =  48_434, AreaSqrKms =   125_443, AdmissionUnionDate = new DateTime(1817, 12, 10), AdmissionUnionOrder = 20, Capital = "Jackson       ", Region = regions[1] };
                states[12] = new Federation() { Abbreviation = "TX", Name = "Texas         ", Area = 268_601, AreaSqrKms =   695_676, AdmissionUnionDate = new DateTime(1845, 12, 29), AdmissionUnionOrder = 28, Capital = "Austin        ", Region = regions[8] };
                states[13] = new Federation() { Abbreviation = "MT", Name = "Montana       ", Area = 147_046, AreaSqrKms =   380_850, AdmissionUnionDate = new DateTime(1889, 11, 08), AdmissionUnionOrder = 41, Capital = "Helena        ", Region = regions[4] };
                states[14] = new Federation() { Abbreviation = "NC", Name = "North Carolina", Area =  53_821, AreaSqrKms =   139_397, AdmissionUnionDate = new DateTime(1789, 11, 21), AdmissionUnionOrder = 12, Capital = "Raleigh       ", Region = regions[6] };
                states[15] = new Federation() { Abbreviation = "TN", Name = "Tennessee     ", Area =  42_146, AreaSqrKms =   109_158, AdmissionUnionDate = new DateTime(1796, 06, 01), AdmissionUnionOrder = 16, Capital = "Nashville     ", Region = regions[1] };
                states[16] = new Federation() { Abbreviation = "NE", Name = "Nebraska      ", Area =  77_358, AreaSqrKms =   200_358, AdmissionUnionDate = new DateTime(1867, 03, 01), AdmissionUnionOrder = 37, Capital = "Lincoln       ", Region = regions[7] };
                states[17] = new Federation() { Abbreviation = "IL", Name = "Illinois      ", Area =  57_918, AreaSqrKms =   150_007, AdmissionUnionDate = new DateTime(1818, 12, 03), AdmissionUnionOrder = 21, Capital = "Springfield   ", Region = regions[0] };
                states[18] = new Federation() { Abbreviation = "KS", Name = "Kansas        ", Area =  82_282, AreaSqrKms =   213_110, AdmissionUnionDate = new DateTime(1861, 01, 29), AdmissionUnionOrder = 34, Capital = "Topeka        ", Region = regions[7] };
                states[19] = new Federation() { Abbreviation = "NH", Name = "New Hampshire ", Area =    9351, AreaSqrKms =    24_219, AdmissionUnionDate = new DateTime(1788, 06, 21), AdmissionUnionOrder =  9, Capital = "Concord       ", Region = regions[2] };
                states[20] = new Federation() { Abbreviation = "DE", Name = "Delaware      ", Area =    2489, AreaSqrKms =      6447, AdmissionUnionDate = new DateTime(1787, 12, 07), AdmissionUnionOrder =  1, Capital = "Dover         ", Region = regions[6] };
                states[21] = new Federation() { Abbreviation = "NJ", Name = "New Jersey    ", Area =    8722, AreaSqrKms =    22_590, AdmissionUnionDate = new DateTime(1787, 12, 18), AdmissionUnionOrder =  3, Capital = "Trenton       ", Region = regions[3] };
                states[22] = new Federation() { Abbreviation = "AK", Name = "Alaska        ", Area = 656_424, AreaSqrKms = 1_700_139, AdmissionUnionDate = new DateTime(1959, 01, 03), AdmissionUnionOrder = 49, Capital = "Juneau        ", Region = regions[5] };
                states[23] = new Federation() { Abbreviation = "NM", Name = "New Mexico    ", Area = 121_598, AreaSqrKms =   314_939, AdmissionUnionDate = new DateTime(1912, 01, 06), AdmissionUnionOrder = 47, Capital = "Santa Fe      ", Region = regions[4] };
                states[24] = new Federation() { Abbreviation = "NY", Name = "New York      ", Area =  54_475, AreaSqrKms =   141_089, AdmissionUnionDate = new DateTime(1788, 07, 26), AdmissionUnionOrder = 11, Capital = "Albany        ", Region = regions[3] };
                states[25] = new Federation() { Abbreviation = "CA", Name = "California    ", Area = 163_707, AreaSqrKms =   424_002, AdmissionUnionDate = new DateTime(1850, 09, 09), AdmissionUnionOrder = 31, Capital = "Sacramento    ", Region = regions[5] };
                states[26] = new Federation() { Abbreviation = "MO", Name = "Missouri      ", Area =  69_709, AreaSqrKms =   180_546, AdmissionUnionDate = new DateTime(1821, 08, 10), AdmissionUnionOrder = 24, Capital = "Jefferson City", Region = regions[7] };
                states[27] = new Federation() { Abbreviation = "OK", Name = "Oklahoma      ", Area =  69_903, AreaSqrKms =   181_049, AdmissionUnionDate = new DateTime(1907, 11, 16), AdmissionUnionOrder = 46, Capital = "Oklahoma City ", Region = regions[8] };
                states[28] = new Federation() { Abbreviation = "PA", Name = "Pennsylvania  ", Area =  46_058, AreaSqrKms =   119_291, AdmissionUnionDate = new DateTime(1787, 12, 12), AdmissionUnionOrder =  2, Capital = "Harrisburg    ", Region = regions[3] };
                states[29] = new Federation() { Abbreviation = "SC", Name = "South Carolina", Area =  32_007, AreaSqrKms =    82_898, AdmissionUnionDate = new DateTime(1788, 05, 23), AdmissionUnionOrder =  8, Capital = "Columbia      ", Region = regions[6] };
                states[30] = new Federation() { Abbreviation = "WY", Name = "Wyoming       ", Area =  97_818, AreaSqrKms =   253_349, AdmissionUnionDate = new DateTime(1890, 07, 10), AdmissionUnionOrder = 44, Capital = "Cheyenne      ", Region = regions[4] };
                states[31] = new Federation() { Abbreviation = "SD", Name = "South Dakota  ", Area =  77_122, AreaSqrKms =   199_745, AdmissionUnionDate = new DateTime(1889, 11, 02), AdmissionUnionOrder = 40, Capital = "Pierre        ", Region = regions[7] };
                states[32] = new Federation() { Abbreviation = "UT", Name = "Utah          ", Area =  84_904, AreaSqrKms =   219_902, AdmissionUnionDate = new DateTime(1896, 01, 04), AdmissionUnionOrder = 45, Capital = "Salt Lake City", Region = regions[4] };
                states[33] = new Federation() { Abbreviation = "AL", Name = "Alabama       ", Area =  52_423, AreaSqrKms =   135_775, AdmissionUnionDate = new DateTime(1819, 12, 14), AdmissionUnionOrder = 22, Capital = "Montgomery    ", Region = regions[1] };
                states[34] = new Federation() { Abbreviation = "VT", Name = "Vermont       ", Area =    9615, AreaSqrKms =    24_903, AdmissionUnionDate = new DateTime(1791, 03, 04), AdmissionUnionOrder = 14, Capital = "Montpelier    ", Region = regions[2] };
                states[35] = new Federation() { Abbreviation = "AR", Name = "Arkansas      ", Area =  53_182, AreaSqrKms =   137_742, AdmissionUnionDate = new DateTime(1836, 06, 15), AdmissionUnionOrder = 25, Capital = "Little Rock   ", Region = regions[8] };
                states[36] = new Federation() { Abbreviation = "WA", Name = "Washington    ", Area =  71_303, AreaSqrKms =   184_674, AdmissionUnionDate = new DateTime(1889, 11, 11), AdmissionUnionOrder = 42, Capital = "Olympia       ", Region = regions[5] };
                states[37] = new Federation() { Abbreviation = "AZ", Name = "Arizona       ", Area = 114_006, AreaSqrKms =   295_276, AdmissionUnionDate = new DateTime(1912, 02, 14), AdmissionUnionOrder = 48, Capital = "Phoenix       ", Region = regions[4] };
                states[38] = new Federation() { Abbreviation = "WV", Name = "West Virginia ", Area =  24_231, AreaSqrKms =    62_759, AdmissionUnionDate = new DateTime(1863, 06, 20), AdmissionUnionOrder = 35, Capital = "Charleston    ", Region = regions[6] };
                states[39] = new Federation() { Abbreviation = "LA", Name = "Louisiana     ", Area =  51_844, AreaSqrKms =   134_275, AdmissionUnionDate = new DateTime(1812, 04, 30), AdmissionUnionOrder = 18, Capital = "Baton Rouge   ", Region = regions[8] };
    
                Array.Resize(ref states, states.Length + 5);
    
                states[40] = new Federation() { Abbreviation = "MA", Name = "Massachusetts ", Area =  10_555, AreaSqrKms =    27_337, AdmissionUnionDate = new DateTime(1788, 02, 06), AdmissionUnionOrder =  6, Capital = "Boston        ", Region = regions[2] };
                states[41] = new Federation() { Abbreviation = "FL", Name = "Florida       ", Area =  65_758, AreaSqrKms =   170_313, AdmissionUnionDate = new DateTime(1845, 03, 03), AdmissionUnionOrder = 27, Capital = "Tallahassee   ", Region = regions[6] };
                states[42] = new Federation() { Abbreviation = "GA", Name = "Georgia       ", Area =  59_441, AreaSqrKms =   153_953, AdmissionUnionDate = new DateTime(1788, 01, 02), AdmissionUnionOrder =  4, Capital = "Atlanta       ", Region = regions[6] };
                states[43] = new Federation() { Abbreviation = "HI", Name = "Hawaii        ", Area =  10_932, AreaSqrKms =    28_313, AdmissionUnionDate = new DateTime(1959, 08, 21), AdmissionUnionOrder = 50, Capital = "Honolulu      ", Region = regions[5] };
                states[44] = new Federation() { Abbreviation = "MD", Name = "Maryland      ", Area =  12_407, AreaSqrKms =    32_135, AdmissionUnionDate = new DateTime(1788, 04, 28), AdmissionUnionOrder =  7, Capital = "Annapolis     ", Region = regions[6] };
    
                Federation[] temporary = new Federation[states.Length + 5];
    
                Array.Copy(states, temporary, states.Length);
    
                states = temporary;
    
                states[45] = new Federation() { Abbreviation = "CO", Name = "Colorado      ", Area = 104_100, AreaSqrKms = 269_620, AdmissionUnionDate = new DateTime(1876, 08, 01), AdmissionUnionOrder = 38, Capital = "Denver        ", Region = regions[4] };
                states[46] = new Federation() { Abbreviation = "MI", Name = "Michigan      ", Area =  98_810, AreaSqrKms = 250_738, AdmissionUnionDate = new DateTime(1837, 01, 26), AdmissionUnionOrder = 26, Capital = "Lansing       ", Region = regions[0] };
                states[47] = new Federation() { Abbreviation = "MN", Name = "Minnesota     ", Area =  86_943, AreaSqrKms = 225_182, AdmissionUnionDate = new DateTime(1858, 05, 11), AdmissionUnionOrder = 32, Capital = "Saint Paul    ", Region = regions[7] };
                states[48] = new Federation() { Abbreviation = "CT", Name = "Connecticut   ", Area =    5544, AreaSqrKms =  14_358, AdmissionUnionDate = new DateTime(1788, 01, 09), AdmissionUnionOrder =  5, Capital = "Hartford      ", Region = regions[3] };
                states[49] = new Federation() { Abbreviation = "NV", Name = "Nevada        ", Area = 110_567, AreaSqrKms = 286_368, AdmissionUnionDate = new DateTime(1864, 10, 31), AdmissionUnionOrder = 36, Capital = "Frankfort     ", Region = regions[4] };
    
                Display(states);
    
                Console.Write("Do you want to sort the list in alphabetical order (y/n)? ");
                string answer = Console.ReadLine();
    
                if (answer.ToLower().Equals("y"))
                {
                    Array.Sort(states);
                    Display(states);
                }
                else
                {
                    Console.WriteLine("Good Bye!!!");
                    Console.WriteLine("====================================================================================================");
                }
    
                return 0;
            }
        }
    }
  39. To execute the project, press Ctrl + F5:
                                     United States of America
    =========================================================================================================
                                     Area      Admission to Union
     # Abbrv State Name        SqrMls     Km2   Date    Order         Capital         Region
    ---------------------------------------------------------------------------------------------------------
     1  RI   Rhode Island       1545       4002    5/29/1790 12:00:00 AM     13        Providence
     2  OH   Ohio              44828     116103    3/1/1803 12:00:00 AM     17        Columbus
     3  KY   Kentucky          40411     104665    6/1/1792 12:00:00 AM     15        Frankfort
     4  IA   Iowa              56276     145754    12/28/1846 12:00:00 AM     29        Des Moines
     5  WI   Wisconsin         65503     169653    5/29/1848 12:00:00 AM     30        Madison
     6  VT   Vermont            9615      24903    3/4/1791 12:00:00 AM     14        Montpelier
     7  ID   Idaho             83574     216456    7/3/1890 12:00:00 AM     43        Boise
     8  ME   Maine             35387      91653    3/15/1820 12:00:00 AM     23        Augusta
     9  OR   Oregon            98386     254819    2/14/1859 12:00:00 AM     33        Salem
    10  ND   North Dakota      70704     183123    11/2/1889 12:00:00 AM     39        Bismarck
    11  IN   Indiana           36420      94328    12/11/1816 12:00:00 AM     19        Indianapolis
    12  MS   Mississippi       48434     125443    12/10/1817 12:00:00 AM     20        Jackson
    13  TX   Texas            268601     695676    12/29/1845 12:00:00 AM     28        Austin
    14  MT   Montana          147046     380850    11/8/1889 12:00:00 AM     41        Helena
    15  NC   North Carolina    53821     139397    11/21/1789 12:00:00 AM     12        Raleigh
    16  TN   Tennessee         42146     109158    6/1/1796 12:00:00 AM     16        Nashville
    17  NE   Nebraska          77358     200358    3/1/1867 12:00:00 AM     37        Lincoln
    18  IL   Illinois          57918     150007    12/3/1818 12:00:00 AM     21        Springfield
    19  KS   Kansas            82282     213110    1/29/1861 12:00:00 AM     34        Topeka
    20  NH   New Hampshire      9351      24219    6/21/1788 12:00:00 AM     9        Concord
    21  DE   Delaware           2489       6447    12/7/1787 12:00:00 AM     1        Dover
    22  NJ   New Jersey         8722      22590    12/18/1787 12:00:00 AM     3        Trenton
    23  AK   Alaska           656424    1700139    1/3/1959 12:00:00 AM     49        Juneau
    24  NM   New Mexico       121598     314939    1/6/1912 12:00:00 AM     47        Santa Fe
    25  NY   New York          54475     141089    7/26/1788 12:00:00 AM     11        Albany
    26  CA   California       163707     424002    9/9/1850 12:00:00 AM     31        Sacramento
    27  MO   Missouri          69709     180546    8/10/1821 12:00:00 AM     24        Jefferson City
    28  OK   Oklahoma          69903     181049    11/16/1907 12:00:00 AM     46        Oklahoma City
    29  PA   Pennsylvania      46058     119291    12/12/1787 12:00:00 AM     2        Harrisburg
    30  SC   South Carolina    32007      82898    5/23/1788 12:00:00 AM     8        Columbia
    31  WY   Wyoming           97818     253349    7/10/1890 12:00:00 AM     44        Cheyenne
    32  SD   South Dakota      77122     199745    11/2/1889 12:00:00 AM     40        Pierre
    33  UT   Utah              84904     219902    1/4/1896 12:00:00 AM     45        Salt Lake City
    34  AL   Alabama           52423     135775    12/14/1819 12:00:00 AM     22        Montgomery
    35  VT   Vermont            9615      24903    3/4/1791 12:00:00 AM     14        Montpelier
    36  AR   Arkansas          53182     137742    6/15/1836 12:00:00 AM     25        Little Rock
    37  WA   Washington        71303     184674    11/11/1889 12:00:00 AM     42        Olympia
    38  AZ   Arizona          114006     295276    2/14/1912 12:00:00 AM     48        Phoenix
    39  WV   West Virginia     24231      62759    6/20/1863 12:00:00 AM     35        Charleston
    40  LA   Louisiana         51844     134275    4/30/1812 12:00:00 AM     18        Baton Rouge
    41  MA   Massachusetts     10555      27337    2/6/1788 12:00:00 AM     6        Boston
    42  FL   Florida           65758     170313    3/3/1845 12:00:00 AM     27        Tallahassee
    43  GA   Georgia           59441     153953    1/2/1788 12:00:00 AM     4        Atlanta
    44  HI   Hawaii            10932      28313    8/21/1959 12:00:00 AM     50        Honolulu
    45  MD   Maryland          12407      32135    4/28/1788 12:00:00 AM     7        Annapolis
    46  CO   Colorado         104100     269620    8/1/1876 12:00:00 AM     38        Denver
    47  MI   Michigan          98810     250738    1/26/1837 12:00:00 AM     26        Lansing
    48  MN   Minnesota         86943     225182    5/11/1858 12:00:00 AM     32        Saint Paul
    49  CT   Connecticut        5544      14358    1/9/1788 12:00:00 AM     5        Hartford
    50  NV   Nevada           110567     286368    10/31/1864 12:00:00 AM     36        Frankfort
    =========================================================================================================
    Do you want to sort the list in alphabetical order (y/n)?
  40. When prompted, type n and press Enter
  41. Press Enter to close the window and return to your programming environment
  42. On the main menu, click File -> Recent Projects and Solutions, and click the option that has GeorgetownDryCleaningServices5.sln

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.

Introduction to Data Formatting

As mentioned earlier, when the user enters a date value for a DateTime variable, the compiler adds a time part to the value. Fortunately, if you want to consider only the date or only the time part, you can specify this to the compiler. To support this, the DateTime data type provides a series of letters you can use to format how its value should be displayed to the user. The character is entered in the placeholder of the DateTime variable after the 0 or the incremental numeric value.

Practical LearningPractical Learning: Controlling Date Formatting

  1. To format a date value, change the document as follows:
    using System;
    
    namespace GeorgetownDryCleaningServices
    {
        class GeorgetownDryCleaningServices
        {
            public static int Main(string[] args)
            {
                . . . No Change
                
    
    
                Console.Clear();
                Console.Title = "Georgetown Dry Cleaning Services";
    
                // Display the receipt
                Console.WriteLine("=========================================");
                Console.WriteLine("-/- Georgetown Dry Cleaning Services -/-");
                Console.WriteLine("=========================================");
                Console.WriteLine("Customer:   {0}", customerName);
                Console.WriteLine("Home Phone: {0}", homePhone);
                Console.WriteLine("Order Date: {0:D}", orderDate);
                Console.WriteLine("-----------------------------------------");
                Console.WriteLine("Item Type    Qty Unit/Price Sub-Total");
                
                . . . No Change
    
                return 0;
            }
        }
    }
  2. To execute the program, on the main menu, click Debug -> Start Without Debugging
  3. Type some values as follows:
    ===============================================
    -/-    Georgetown Dry Cleaning Services    -/-
    ==============================================
    Enter Customer Name:                Catherine Richardson
    Enter Customer Phone:               (202) 184-9738
    Enter the order date (mm/dd/yyyy):  27 May 2019
    Number of Shirts:                   8
    Number of Pants:                    12
    Number of Other Items:              14
    -----------------------------------------
    The Total order is:                 $88.94
    Amount Tended?                      90
  4. Press Enter:
    =========================================
    -/- Georgetown Dry Cleaning Services -/-
    =========================================
    Customer:   Catherine Richardson
    Home Phone: (202) 184-9738
    Order Date: Monday, May 27, 2019
    -----------------------------------------
    Item Type    Qty Unit/Price Sub-Total
    -----------------------------------------
    Shirts        8     $1.25     $10.00
    Pants        12     $2.15     $25.80
    Other Items  14     $3.45     $48.30
    -----------------------------------------
    Total Order:     $84.10
    Tax Rate:        5.75 %
    Tax Amount:      $4.84
    Net Price:       $88.94
    -----------------------------------------
    Amount Tended:   $90.00
    Difference:      $1.06
    =========================================
    Press any key to continue . . .
  5. Press Enter to close the DOS window and return to your programming environment
  6. Close your programming environment
  7. On the main menu, click File -> Recent Projects and Solutions, and click the option that has CountriesStatistics.sln

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.

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

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 . . .

To support short date formats, the DateTime structure is equipped with a method named ToShortDateString. Its syntax is:

public string ToShortDateString();

Practical LearningPractical Learning: Getting a Short Date String

  1. Change the document as follows:
    using System;
    
    namespace CountriesStatistics4
    {
        public class CountriesStatistics
        {
            private static void Display(Array entities)
            {
                Console.Clear();
    
                Console.WriteLine("                                 United States of America");
                Console.WriteLine("=========================================================================================================");
                Console.WriteLine("                                 Area        Admission to Union");
                Console.WriteLine(" # Abbrv State Name        SqrMls     Km2          Date      Order    Capital         Region");
                Console.WriteLine("---------------------------------------------------------------------------------------------------------");
    
                for (int counter = 0; counter <= entities.Length - 1; counter++)
                {
                    Federation stt = (Federation)entities.GetValue(counter);
    
                    Console.WriteLine("{0,2}  {1,2}   {2}   {3,6}   {4,8}    {5,10}    {6,3}      {7}  {8}",
                                      counter + 1, stt.Abbreviation, stt.StateName,
                                      stt.AreaSqrMiles, stt.AreaSqrKms, stt.AdmissionUnionDate.ToShortDateString(),
                                      stt.AdmissionUnionOrder, stt.Capital, stt.Region.Designation);
                }
                Console.WriteLine("=========================================================================================================");
            }
    
            public static int Main(string[] args)
            {
                Region[] regions = new Region[]
                   {
                    new Region() { Designation = "East North Central", Description = "The East North Central region includes the states around the Great Lakes." },
                    new Region() { Designation = "East South Central", Description = "The East South Central portion is one of the regions designated as the South." },
                    new Region() { Designation = "New England       ", Description = "New England is the group of states in the North-East region. It is delimited in the North and North-East by Canada, in the East by the Atlantic Ocean, and in the South and West by the New York state." },
                    new Region() { Designation = "Mid-Atlantic      ", Description = "Mid-Atlantic is a region situated in the south of New England. Mid-Atlantic is one of the regions defined by the Census bureau for statistical purposes." },
                    new Region() { Designation = "Mountain          ", Description = "Like the name suggests, the Mountain region covers states known for their mountaneous characteristics. They are also covered by desertic areas." },
                    new Region() { Designation = "Pacific           ", Description = "The Pacific region covers the costal western states plus the two non-continental states of Alaska and the Hawaiian islands. All states in this region have a coast on the Pacific Ocean." },
                    new Region() { Designation = "South Atlantic    ", Description = "The South Atlantic region includes the states in the South-East part but also counts the Disctrict of Columbia." },
                    new Region() { Designation = "West North Central", Description = "The West North Central region includes the states in the Great Planes area. This reqion is divided from the East North Central part by the Mississippi River. This region is characterized by vast agricultural farms and high employment." },
                    new Region() { Designation = "West South Central", Description = "The West South Central part is one of the regions with (only) four states. The imposing Texas state is both the largest and the most populous state in the region." }
                   };
    
                Federation[] states = new Federation[40];
    
                states[0]  = new Federation() { Abbreviation = "RI", Name = "Rhode Island  ", Area =    1545, AreaSqrKms =      4002, AdmissionUnionDate = new DateTime(1790, 05, 29), AdmissionUnionOrder = 13, Capital = "Providence    ", Region = regions[2] };
                states[1]  = new Federation() { Abbreviation = "OH", Name = "Ohio          ", Area =  44_828, AreaSqrKms =   116_103, AdmissionUnionDate = new DateTime(1803, 03, 01), AdmissionUnionOrder = 17, Capital = "Columbus      ", Region = regions[0] };
                states[2]  = new Federation() { Abbreviation = "KY", Name = "Kentucky      ", Area =  40_411, AreaSqrKms =   104_665, AdmissionUnionDate = new DateTime(1792, 06, 01), AdmissionUnionOrder = 15, Capital = "Frankfort     ", Region = regions[2] };
                states[3]  = new Federation() { Abbreviation = "IA", Name = "Iowa          ", Area =  56_276, AreaSqrKms =   145_754, AdmissionUnionDate = new DateTime(1846, 12, 28), AdmissionUnionOrder = 29, Capital = "Des Moines    ", Region = regions[7] };
                states[4]  = new Federation() { Abbreviation = "WI", Name = "Wisconsin     ", Area =  65_503, AreaSqrKms =   169_653, AdmissionUnionDate = new DateTime(1848, 05, 29), AdmissionUnionOrder = 30, Capital = "Madison       ", Region = regions[0] };
                states[5]  = new Federation() { Abbreviation = "VT", Name = "Vermont       ", Area =    9615, AreaSqrKms =    24_903, AdmissionUnionDate = new DateTime(1791, 03, 04), AdmissionUnionOrder = 14, Capital = "Montpelier    ", Region = regions[2] };
                states[6]  = new Federation() { Abbreviation = "ID", Name = "Idaho         ", Area =  83_574, AreaSqrKms =   216_456, AdmissionUnionDate = new DateTime(1890, 07, 03), AdmissionUnionOrder = 43, Capital = "Boise         ", Region = regions[4] };
                states[7]  = new Federation() { Abbreviation = "ME", Name = "Maine         ", Area =  35_387, AreaSqrKms =    91_653, AdmissionUnionDate = new DateTime(1820, 03, 15), AdmissionUnionOrder = 23, Capital = "Augusta       ", Region = regions[2] };
                states[8]  = new Federation() { Abbreviation = "OR", Name = "Oregon        ", Area =  98_386, AreaSqrKms =   254_819, AdmissionUnionDate = new DateTime(1859, 02, 14), AdmissionUnionOrder = 33, Capital = "Salem         ", Region = regions[5] };
                states[9]  = new Federation() { Abbreviation = "ND", Name = "North Dakota  ", Area =  70_704, AreaSqrKms =   183_123, AdmissionUnionDate = new DateTime(1889, 11, 02), AdmissionUnionOrder = 39, Capital = "Bismarck      ", Region = regions[7] };
                states[10] = new Federation() { Abbreviation = "IN", Name = "Indiana       ", Area =  36_420, AreaSqrKms =    94_328, AdmissionUnionDate = new DateTime(1816, 12, 11), AdmissionUnionOrder = 19, Capital = "Indianapolis  ", Region = regions[0] };
                states[11] = new Federation() { Abbreviation = "MS", Name = "Mississippi   ", Area =  48_434, AreaSqrKms =   125_443, AdmissionUnionDate = new DateTime(1817, 12, 10), AdmissionUnionOrder = 20, Capital = "Jackson       ", Region = regions[1] };
                states[12] = new Federation() { Abbreviation = "TX", Name = "Texas         ", Area = 268_601, AreaSqrKms =   695_676, AdmissionUnionDate = new DateTime(1845, 12, 29), AdmissionUnionOrder = 28, Capital = "Austin        ", Region = regions[8] };
                states[13] = new Federation() { Abbreviation = "MT", Name = "Montana       ", Area = 147_046, AreaSqrKms =   380_850, AdmissionUnionDate = new DateTime(1889, 11, 08), AdmissionUnionOrder = 41, Capital = "Helena        ", Region = regions[4] };
                states[14] = new Federation() { Abbreviation = "NC", Name = "North Carolina", Area =  53_821, AreaSqrKms =   139_397, AdmissionUnionDate = new DateTime(1789, 11, 21), AdmissionUnionOrder = 12, Capital = "Raleigh       ", Region = regions[6] };
                states[15] = new Federation() { Abbreviation = "TN", Name = "Tennessee     ", Area =  42_146, AreaSqrKms =   109_158, AdmissionUnionDate = new DateTime(1796, 06, 01), AdmissionUnionOrder = 16, Capital = "Nashville     ", Region = regions[1] };
                states[16] = new Federation() { Abbreviation = "NE", Name = "Nebraska      ", Area =  77_358, AreaSqrKms =   200_358, AdmissionUnionDate = new DateTime(1867, 03, 01), AdmissionUnionOrder = 37, Capital = "Lincoln       ", Region = regions[7] };
                states[17] = new Federation() { Abbreviation = "IL", Name = "Illinois      ", Area =  57_918, AreaSqrKms =   150_007, AdmissionUnionDate = new DateTime(1818, 12, 03), AdmissionUnionOrder = 21, Capital = "Springfield   ", Region = regions[0] };
                states[18] = new Federation() { Abbreviation = "KS", Name = "Kansas        ", Area =  82_282, AreaSqrKms =   213_110, AdmissionUnionDate = new DateTime(1861, 01, 29), AdmissionUnionOrder = 34, Capital = "Topeka        ", Region = regions[7] };
                states[19] = new Federation() { Abbreviation = "NH", Name = "New Hampshire ", Area =    9351, AreaSqrKms =    24_219, AdmissionUnionDate = new DateTime(1788, 06, 21), AdmissionUnionOrder =  9, Capital = "Concord       ", Region = regions[2] };
                states[20] = new Federation() { Abbreviation = "DE", Name = "Delaware      ", Area =    2489, AreaSqrKms =      6447, AdmissionUnionDate = new DateTime(1787, 12, 07), AdmissionUnionOrder =  1, Capital = "Dover         ", Region = regions[6] };
                states[21] = new Federation() { Abbreviation = "NJ", Name = "New Jersey    ", Area =    8722, AreaSqrKms =    22_590, AdmissionUnionDate = new DateTime(1787, 12, 18), AdmissionUnionOrder =  3, Capital = "Trenton       ", Region = regions[3] };
                states[22] = new Federation() { Abbreviation = "AK", Name = "Alaska        ", Area = 656_424, AreaSqrKms = 1_700_139, AdmissionUnionDate = new DateTime(1959, 01, 03), AdmissionUnionOrder = 49, Capital = "Juneau        ", Region = regions[5] };
                states[23] = new Federation() { Abbreviation = "NM", Name = "New Mexico    ", Area = 121_598, AreaSqrKms =   314_939, AdmissionUnionDate = new DateTime(1912, 01, 06), AdmissionUnionOrder = 47, Capital = "Santa Fe      ", Region = regions[4] };
                states[24] = new Federation() { Abbreviation = "NY", Name = "New York      ", Area =  54_475, AreaSqrKms =   141_089, AdmissionUnionDate = new DateTime(1788, 07, 26), AdmissionUnionOrder = 11, Capital = "Albany        ", Region = regions[3] };
                states[25] = new Federation() { Abbreviation = "CA", Name = "California    ", Area = 163_707, AreaSqrKms =   424_002, AdmissionUnionDate = new DateTime(1850, 09, 09), AdmissionUnionOrder = 31, Capital = "Sacramento    ", Region = regions[5] };
                states[26] = new Federation() { Abbreviation = "MO", Name = "Missouri      ", Area =  69_709, AreaSqrKms =   180_546, AdmissionUnionDate = new DateTime(1821, 08, 10), AdmissionUnionOrder = 24, Capital = "Jefferson City", Region = regions[7] };
                states[27] = new Federation() { Abbreviation = "OK", Name = "Oklahoma      ", Area =  69_903, AreaSqrKms =   181_049, AdmissionUnionDate = new DateTime(1907, 11, 16), AdmissionUnionOrder = 46, Capital = "Oklahoma City ", Region = regions[8] };
                states[28] = new Federation() { Abbreviation = "PA", Name = "Pennsylvania  ", Area =  46_058, AreaSqrKms =   119_291, AdmissionUnionDate = new DateTime(1787, 12, 12), AdmissionUnionOrder =  2, Capital = "Harrisburg    ", Region = regions[3] };
                states[29] = new Federation() { Abbreviation = "SC", Name = "South Carolina", Area =  32_007, AreaSqrKms =    82_898, AdmissionUnionDate = new DateTime(1788, 05, 23), AdmissionUnionOrder =  8, Capital = "Columbia      ", Region = regions[6] };
                states[30] = new Federation() { Abbreviation = "WY", Name = "Wyoming       ", Area =  97_818, AreaSqrKms =   253_349, AdmissionUnionDate = new DateTime(1890, 07, 10), AdmissionUnionOrder = 44, Capital = "Cheyenne      ", Region = regions[4] };
                states[31] = new Federation() { Abbreviation = "SD", Name = "South Dakota  ", Area =  77_122, AreaSqrKms =   199_745, AdmissionUnionDate = new DateTime(1889, 11, 02), AdmissionUnionOrder = 40, Capital = "Pierre        ", Region = regions[7] };
                states[32] = new Federation() { Abbreviation = "UT", Name = "Utah          ", Area =  84_904, AreaSqrKms =   219_902, AdmissionUnionDate = new DateTime(1896, 01, 04), AdmissionUnionOrder = 45, Capital = "Salt Lake City", Region = regions[4] };
                states[33] = new Federation() { Abbreviation = "AL", Name = "Alabama       ", Area =  52_423, AreaSqrKms =   135_775, AdmissionUnionDate = new DateTime(1819, 12, 14), AdmissionUnionOrder = 22, Capital = "Montgomery    ", Region = regions[1] };
                states[34] = new Federation() { Abbreviation = "VT", Name = "Vermont       ", Area =    9615, AreaSqrKms =    24_903, AdmissionUnionDate = new DateTime(1791, 03, 04), AdmissionUnionOrder = 14, Capital = "Montpelier    ", Region = regions[2] };
                states[35] = new Federation() { Abbreviation = "AR", Name = "Arkansas      ", Area =  53_182, AreaSqrKms =   137_742, AdmissionUnionDate = new DateTime(1836, 06, 15), AdmissionUnionOrder = 25, Capital = "Little Rock   ", Region = regions[8] };
                states[36] = new Federation() { Abbreviation = "WA", Name = "Washington    ", Area =  71_303, AreaSqrKms =   184_674, AdmissionUnionDate = new DateTime(1889, 11, 11), AdmissionUnionOrder = 42, Capital = "Olympia       ", Region = regions[5] };
                states[37] = new Federation() { Abbreviation = "AZ", Name = "Arizona       ", Area = 114_006, AreaSqrKms =   295_276, AdmissionUnionDate = new DateTime(1912, 02, 14), AdmissionUnionOrder = 48, Capital = "Phoenix       ", Region = regions[4] };
                states[38] = new Federation() { Abbreviation = "WV", Name = "West Virginia ", Area =  24_231, AreaSqrKms =    62_759, AdmissionUnionDate = new DateTime(1863, 06, 20), AdmissionUnionOrder = 35, Capital = "Charleston    ", Region = regions[6] };
                states[39] = new Federation() { Abbreviation = "LA", Name = "Louisiana     ", Area =  51_844, AreaSqrKms =   134_275, AdmissionUnionDate = new DateTime(1812, 04, 30), AdmissionUnionOrder = 18, Capital = "Baton Rouge   ", Region = regions[8] };
    
                Array.Resize(ref states, states.Length + 5);
    
                states[40] = new Federation() { Abbreviation = "MA", Name = "Massachusetts ", Area =  10_555, AreaSqrKms =    27_337, AdmissionUnionDate = new DateTime(1788, 02, 06), AdmissionUnionOrder =  6, Capital = "Boston        ", Region = regions[2] };
                states[41] = new Federation() { Abbreviation = "FL", Name = "Florida       ", Area =  65_758, AreaSqrKms =   170_313, AdmissionUnionDate = new DateTime(1845, 03, 03), AdmissionUnionOrder = 27, Capital = "Tallahassee   ", Region = regions[6] };
                states[42] = new Federation() { Abbreviation = "GA", Name = "Georgia       ", Area =  59_441, AreaSqrKms =   153_953, AdmissionUnionDate = new DateTime(1788, 01, 02), AdmissionUnionOrder =  4, Capital = "Atlanta       ", Region = regions[6] };
                states[43] = new Federation() { Abbreviation = "HI", Name = "Hawaii        ", Area =  10_932, AreaSqrKms =    28_313, AdmissionUnionDate = new DateTime(1959, 08, 21), AdmissionUnionOrder = 50, Capital = "Honolulu      ", Region = regions[5] };
                states[44] = new Federation() { Abbreviation = "MD", Name = "Maryland      ", Area =  12_407, AreaSqrKms =    32_135, AdmissionUnionDate = new DateTime(1788, 04, 28), AdmissionUnionOrder =  7, Capital = "Annapolis     ", Region = regions[6] };
    
                Federation[] temporary = new Federation[states.Length + 5];
    
                Array.Copy(states, temporary, states.Length);
    
                states = temporary;
    
                states[45] = new Federation() { Abbreviation = "CO", Name = "Colorado      ", Area = 104_100, AreaSqrKms = 269_620, AdmissionUnionDate = new DateTime(1876, 08, 01), AdmissionUnionOrder = 38, Capital = "Denver        ", Region = regions[4] };
                states[46] = new Federation() { Abbreviation = "MI", Name = "Michigan      ", Area =  98_810, AreaSqrKms = 250_738, AdmissionUnionDate = new DateTime(1837, 01, 26), AdmissionUnionOrder = 26, Capital = "Lansing       ", Region = regions[0] };
                states[47] = new Federation() { Abbreviation = "MN", Name = "Minnesota     ", Area =  86_943, AreaSqrKms = 225_182, AdmissionUnionDate = new DateTime(1858, 05, 11), AdmissionUnionOrder = 32, Capital = "Saint Paul    ", Region = regions[7] };
                states[48] = new Federation() { Abbreviation = "CT", Name = "Connecticut   ", Area =    5544, AreaSqrKms =  14_358, AdmissionUnionDate = new DateTime(1788, 01, 09), AdmissionUnionOrder =  5, Capital = "Hartford      ", Region = regions[3] };
                states[49] = new Federation() { Abbreviation = "NV", Name = "Nevada        ", Area = 110_567, AreaSqrKms = 286_368, AdmissionUnionDate = new DateTime(1864, 10, 31), AdmissionUnionOrder = 36, Capital = "Frankfort     ", Region = regions[4] };
    
                Display(states);
    
                Console.Write("Do you want to sort the list in alphabetical order (y/n)? ");
                string answer = Console.ReadLine();
    
                if (answer.ToLower().Equals("y"))
                {
                    Array.Sort(states);
                    Display(states);
                }
                else
                {
                    Console.WriteLine("Good Bye!!!");
                    Console.WriteLine("====================================================================================================");
                }
    
                return 0;
            }
        }
    }
  2. To execute, on the main menu, click Debug -> Start Without Debugging:
                                     United States of America
    =========================================================================================================
                                     Area        Admission to Union
     # Abbrv State Name        SqrMls     Km2          Date      Order    Capital         Region
    ---------------------------------------------------------------------------------------------------------
     1  RI   Rhode Island       1545       4002     5/29/1790     13      Providence      New England
     2  OH   Ohio              44828     116103      3/1/1803     17      Columbus        East North Central
     3  KY   Kentucky          40411     104665      6/1/1792     15      Frankfort       New England
     4  IA   Iowa              56276     145754    12/28/1846     29      Des Moines      West North Central
     5  WI   Wisconsin         65503     169653     5/29/1848     30      Madison         East North Central
     6  VT   Vermont            9615      24903      3/4/1791     14      Montpelier      New England
     7  ID   Idaho             83574     216456      7/3/1890     43      Boise           Mountain
     8  ME   Maine             35387      91653     3/15/1820     23      Augusta         New England
     9  OR   Oregon            98386     254819     2/14/1859     33      Salem           Pacific
    10  ND   North Dakota      70704     183123     11/2/1889     39      Bismarck        West North Central
    11  IN   Indiana           36420      94328    12/11/1816     19      Indianapolis    East North Central
    12  MS   Mississippi       48434     125443    12/10/1817     20      Jackson         East South Central
    13  TX   Texas            268601     695676    12/29/1845     28      Austin          West South Central
    14  MT   Montana          147046     380850     11/8/1889     41      Helena          Mountain
    15  NC   North Carolina    53821     139397    11/21/1789     12      Raleigh         South Atlantic
    16  TN   Tennessee         42146     109158      6/1/1796     16      Nashville       East South Central
    17  NE   Nebraska          77358     200358      3/1/1867     37      Lincoln         West North Central
    18  IL   Illinois          57918     150007     12/3/1818     21      Springfield     East North Central
    19  KS   Kansas            82282     213110     1/29/1861     34      Topeka          West North Central
    20  NH   New Hampshire      9351      24219     6/21/1788      9      Concord         New England
    21  DE   Delaware           2489       6447     12/7/1787      1      Dover           South Atlantic
    22  NJ   New Jersey         8722      22590    12/18/1787      3      Trenton         Mid-Atlantic
    23  AK   Alaska           656424    1700139      1/3/1959     49      Juneau          Pacific
    24  NM   New Mexico       121598     314939      1/6/1912     47      Santa Fe        Mountain
    25  NY   New York          54475     141089     7/26/1788     11      Albany          Mid-Atlantic
    26  CA   California       163707     424002      9/9/1850     31      Sacramento      Pacific
    27  MO   Missouri          69709     180546     8/10/1821     24      Jefferson City  West North Central
    28  OK   Oklahoma          69903     181049    11/16/1907     46      Oklahoma City   West South Central
    29  PA   Pennsylvania      46058     119291    12/12/1787      2      Harrisburg      Mid-Atlantic
    30  SC   South Carolina    32007      82898     5/23/1788      8      Columbia        South Atlantic
    31  WY   Wyoming           97818     253349     7/10/1890     44      Cheyenne        Mountain
    32  SD   South Dakota      77122     199745     11/2/1889     40      Pierre          West North Central
    33  UT   Utah              84904     219902      1/4/1896     45      Salt Lake City  Mountain
    34  AL   Alabama           52423     135775    12/14/1819     22      Montgomery      East South Central
    35  VT   Vermont            9615      24903      3/4/1791     14      Montpelier      New England
    36  AR   Arkansas          53182     137742     6/15/1836     25      Little Rock     West South Central
    37  WA   Washington        71303     184674    11/11/1889     42      Olympia         Pacific
    38  AZ   Arizona          114006     295276     2/14/1912     48      Phoenix         Mountain
    39  WV   West Virginia     24231      62759     6/20/1863     35      Charleston      South Atlantic
    40  LA   Louisiana         51844     134275     4/30/1812     18      Baton Rouge     West South Central
    41  MA   Massachusetts     10555      27337      2/6/1788      6      Boston          New England
    42  FL   Florida           65758     170313      3/3/1845     27      Tallahassee     South Atlantic
    43  GA   Georgia           59441     153953      1/2/1788      4      Atlanta         South Atlantic
    44  HI   Hawaii            10932      28313     8/21/1959     50      Honolulu        Pacific
    45  MD   Maryland          12407      32135     4/28/1788      7      Annapolis       South Atlantic
    46  CO   Colorado         104100     269620      8/1/1876     38      Denver          Mountain
    47  MI   Michigan          98810     250738     1/26/1837     26      Lansing         East North Central
    48  MN   Minnesota         86943     225182     5/11/1858     32      Saint Paul      West North Central
    49  CT   Connecticut        5544      14358      1/9/1788      5      Hartford        Mid-Atlantic
    50  NV   Nevada           110567     286368    10/31/1864     36      Frankfort       Mountain
    =========================================================================================================
    Do you want to sort the list in alphabetical order (y/n)?
  3. When prompted, type Y and press Enter
                                     United States of America
    =========================================================================================================
                                     Area        Admission to Union
     # Abbrv State Name        SqrMls     Km2          Date      Order    Capital         Region
    ---------------------------------------------------------------------------------------------------------
     1  AL   Alabama           52423     135775    12/14/1819     22      Montgomery      East South Central
     2  AK   Alaska           656424    1700139      1/3/1959     49      Juneau          Pacific
     3  AZ   Arizona          114006     295276     2/14/1912     48      Phoenix         Mountain
     4  AR   Arkansas          53182     137742     6/15/1836     25      Little Rock     West South Central
     5  CA   California       163707     424002      9/9/1850     31      Sacramento      Pacific
     6  CO   Colorado         104100     269620      8/1/1876     38      Denver          Mountain
     7  CT   Connecticut        5544      14358      1/9/1788      5      Hartford        Mid-Atlantic
     8  DE   Delaware           2489       6447     12/7/1787      1      Dover           South Atlantic
     9  FL   Florida           65758     170313      3/3/1845     27      Tallahassee     South Atlantic
    10  GA   Georgia           59441     153953      1/2/1788      4      Atlanta         South Atlantic
    11  HI   Hawaii            10932      28313     8/21/1959     50      Honolulu        Pacific
    12  ID   Idaho             83574     216456      7/3/1890     43      Boise           Mountain
    13  IL   Illinois          57918     150007     12/3/1818     21      Springfield     East North Central
    14  IN   Indiana           36420      94328    12/11/1816     19      Indianapolis    East North Central
    15  IA   Iowa              56276     145754    12/28/1846     29      Des Moines      West North Central
    16  KS   Kansas            82282     213110     1/29/1861     34      Topeka          West North Central
    17  KY   Kentucky          40411     104665      6/1/1792     15      Frankfort       New England
    18  LA   Louisiana         51844     134275     4/30/1812     18      Baton Rouge     West South Central
    19  ME   Maine             35387      91653     3/15/1820     23      Augusta         New England
    20  MD   Maryland          12407      32135     4/28/1788      7      Annapolis       South Atlantic
    21  MA   Massachusetts     10555      27337      2/6/1788      6      Boston          New England
    22  MI   Michigan          98810     250738     1/26/1837     26      Lansing         East North Central
    23  MN   Minnesota         86943     225182     5/11/1858     32      Saint Paul      West North Central
    24  MS   Mississippi       48434     125443    12/10/1817     20      Jackson         East South Central
    25  MO   Missouri          69709     180546     8/10/1821     24      Jefferson City  West North Central
    26  MT   Montana          147046     380850     11/8/1889     41      Helena          Mountain
    27  NE   Nebraska          77358     200358      3/1/1867     37      Lincoln         West North Central
    28  NV   Nevada           110567     286368    10/31/1864     36      Frankfort       Mountain
    29  NH   New Hampshire      9351      24219     6/21/1788      9      Concord         New England
    30  NJ   New Jersey         8722      22590    12/18/1787      3      Trenton         Mid-Atlantic
    31  NM   New Mexico       121598     314939      1/6/1912     47      Santa Fe        Mountain
    32  NY   New York          54475     141089     7/26/1788     11      Albany          Mid-Atlantic
    33  NC   North Carolina    53821     139397    11/21/1789     12      Raleigh         South Atlantic
    34  ND   North Dakota      70704     183123     11/2/1889     39      Bismarck        West North Central
    35  OH   Ohio              44828     116103      3/1/1803     17      Columbus        East North Central
    36  OK   Oklahoma          69903     181049    11/16/1907     46      Oklahoma City   West South Central
    37  OR   Oregon            98386     254819     2/14/1859     33      Salem           Pacific
    38  PA   Pennsylvania      46058     119291    12/12/1787      2      Harrisburg      Mid-Atlantic
    39  RI   Rhode Island       1545       4002     5/29/1790     13      Providence      New England
    40  SC   South Carolina    32007      82898     5/23/1788      8      Columbia        South Atlantic
    41  SD   South Dakota      77122     199745     11/2/1889     40      Pierre          West North Central
    42  TN   Tennessee         42146     109158      6/1/1796     16      Nashville       East South Central
    43  TX   Texas            268601     695676    12/29/1845     28      Austin          West South Central
    44  UT   Utah              84904     219902      1/4/1896     45      Salt Lake City  Mountain
    45  VT   Vermont            9615      24903      3/4/1791     14      Montpelier      New England
    46  VT   Vermont            9615      24903      3/4/1791     14      Montpelier      New England
    47  WA   Washington        71303     184674    11/11/1889     42      Olympia         Pacific
    48  WV   West Virginia     24231      62759     6/20/1863     35      Charleston      South Atlantic
    49  WI   Wisconsin         65503     169653     5/29/1848     30      Madison         East North Central
    50  WY   Wyoming           97818     253349     7/10/1890     44      Cheyenne        Mountain
    =========================================================================================================
    Press any key to continue . . .
  4. Press Enter to close the window and return to your programming environment

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 . . .

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 . . .

Practical LearningPractical Learning: Ending the Lesson

  1. Close your programming environment

Previous Copyright © 2008-2019, FunctionX Next