Introduction to Date Values |
|
Dates Fundamentals
Introduction
A date is a measure of non-spatial units that have elapsed in a set period. A group of seven consecutive days is called a week. The days of a week are named in US English as Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, and Sunday. These are referred to as long names. The corresponding short names in US English are Mon, Tue, Wed, Thu, Fri, Sat, and Sun. In US English, Sunday is usually considered the first day of the week.
The months are counted from 1 and up. Each month holds a long name. In US English, they are January, February, March, April, May, June, July, August, September, October, November, and December. Their short names in US English are Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, and Dec.
A group of four months is called a quarter. A group of twelve months can be called a year. The .NET Framework compilers count the years from 0001 to 9999. In a regular year, the months are counted from 1 to 12.
The technique or expression used to identify a particular day during a year is called a date. The days are counted from 1 to 365 or 366 (depending on a factor called a leap year). A date can be the combination of a day, its month, and the year.
The technique or expression used to identify a particular unit of measure during a day is called the time. It can be the combination of the hour, the minute, and the second.
Practical Learning: Introducing Date/Time Values
Control | (Name) | Text | TextAlign |
Label | United Mexican States | Font: Georgia, 20.25pt, style=Bold | |
Label | ______________________ | ||
ListView | lvwStates |
View: Details GridLines: True FullRowSelect: True Anchor: Top, Bottom, Left, Right |
List View Columns
(Name) | Text | TextAlign | Width |
colNumber | # | 25 | |
colStateName | State Name | 100 | |
colAreaSqrKms | Area (Sqr Kms) | Right | 90 |
colAreaSqrMiles | Area (Sqr Ml) | Right | 80 |
colAdmissionToFederationDate | Adm to Fedrt (Date) | Center | 120 |
colAdmissionToFederationOrder | Adm to Fedrt (Order) | Center | 110 |
colCapital | Capital | 150 |
Date Value Creation
To let you create and manage dates, the .NET Framework provides a structure named DateTime. To create a date or a time 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:
public class Exercise
{
public static int Main(string[] args)
{
DateTime tm = new DateTime();
}
}
After declaring a DateTime variable and initializing it, it holds all necessary pieces of information about its date and its time values.
Initializing a Date Object
A date is a technique of identifying a period using three numbers: the year, the month, and the day. Each is an integer value. If you know the values you want to use to create or specify a date value, when declaring a DateTime variable, you can use the following constructor:
public DateTime(int year, int month, int day);
Here is an example of creating a date:
using System;
using static System.Console;
public class Exercise
{
public static int Main(string[] args)
{
DateTime independance = new DateTime(1960, 1, 1);
Title = "Date Values";
WriteLine("Independence Day: {0}", independance);
WriteLine("=======================================");
return 0;
}
}
This would produce:
Independence Day: 1/1/1960 12:00:00 AM ======================================= Press any key to continue . . .
Converting a String to Date
Before displaying a DateTime value on a form, you can first convert that value to a string. To support this, the DateTime structure overrides 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.
Formatting a String for a Date
As you may know already, the string data type is equipped with the overloaded Format() method that allows you to control the content of a string. In the first argument of this method, you can create one or more {} placeholders to specify how the value should appear.
String Interpolation
String interpolation is another technique used to format a string. You use it by starting a string with $ and including the traditional double-quotes. In the quotes, create the neccessary {} placeholders. In a placeholder, type the name of a DateTime variable, a colon, and a format.
A Date as a Type
Introduction
As we will see in various examples, the DateTime type is used like any structure or type. Besides using it to declare variables, you can pass it as argument to a function or method and you can return its value from a function or method.
A Field of a Date Type
You can create a field that is a date/time type as a member of a class. You can declare the variable in the body of the class and initialize it in a method of the class. The initialization is typically done in a constructor. Here is an example:
using System;
public class Employee
{
private DateTime dtHired;
public State()
{
dt = new DateTime(2018, 5, 26);
}
}
A Date Property
A property of DateTime type is created like that of a structure. Whenever you need to initialize it or give it a value, proceed as for any structure.
An Array of Date Values
To create an array of dates, times, or date and time combinations, declare the variable as an array. To initialize the array, you can provide a value for each item using a constructor of the DateTime structure. Here is an example:
DateTime[] dateOfAdmissionToFederation = new DateTime[] { new DateTime(1823, 12, 20), new DateTime(1824, 2, 7), new DateTime(1823, 12, 22), new DateTime(1824, 5, 7), new DateTime(1824, 7, 6), new DateTime(1952, 1, 16), new DateTime(1917, 1, 26), new DateTime(1823, 12, 21), new DateTime(1823, 12, 21), new DateTime(1869, 4, 17), new DateTime(1824, 1, 10), new DateTime(1857, 2, 5), };
Presenting Date Values
Normally, a DateTime value is presented like any value of a primitive type. In a form, you can just provide the name of the variable. The form would display the value using some default settings.
Practical Learning: Presenting an Array of Date Values
using System; using System.Windows.Forms; namespace CountriesStatistics4 { public partial class Form1 : Form { public Form1() { InitializeComponent(); Present(); } void Present() { string[] states = new string[31]; states[0] = "Guanajuato"; states[1] = "Tamaulipas"; states[2] = "Michoacán"; states[3] = "Coahuila"; states[4] = "Chihuahua"; states[5] = "Baja California Sur"; states[6] = "Nayarit"; states[7] = "Puebla"; states[8] = "Oaxaca"; states[9] = "Morelos"; states[10] = "Sonora"; states[11] = "Aguascalientes"; states[12] = "Baja California"; states[13] = "Tabasco"; states[14] = "Jalisco"; states[15] = "México"; states[16] = "Guerrero"; states[17] = "Colima"; states[18] = "Zacatecas"; states[19] = "Sinaloa"; states[20] = "Campeche"; states[21] = "Quintana Roo"; states[22] = "Nuevo León"; states[23] = "Hidalgo"; states[24] = "Tlaxcala"; states[25] = "Yucatán"; states[26] = "Querétaro"; states[27] = "Veracruz"; states[28] = "San Luis Potosí"; states[29] = "Durango"; states[30] = "Chiapas"; string[] capitals = new string[] { "Guanajuato", "Ciudad Victoria", "Morelia", "Saltillo", "Chihuahua", "La Paz", "Tepic", "Puebla de Zaragoza", "Oaxaca de Juárez", "Cuernavaca", "Hermosillo", "Aguascalientes", "Mexicali", "Villahermosa", "Guadalajara", "Toluca de Lerdo", "Chilpancingo de los Bravo", "Colima", "Zacatecas", "Culiacán", "San Francisco de Campeche", "Chetumal", "Monterrey", "Pachuca", "Tlaxcala", "Mérida", "Santiago de Querétaro", "Xalapa", "San Luis Potosí", "Victoria de Durango", "Tuxtla Gutiérrez"}; int[] areasSqrKms = new int[] { 30608, 80175, 58643, 151563, 247455, 73922, 27815, 34290, 93793, 4893, 179503, 5618, 71446, 24738, 78599, 22357, 63621, 5625, 75539, 57377, 57924, 42361, 64220, 20846, 3991, 39612, 11684, 71820, 60983, 123451, 73289 }; int[] areasSqrMiles = new int[] { 11818, 30956, 22642, 58519, 95543, 28541, 10739, 13240, 36214, 1889, 69306, 2169, 27585, 9551, 30347, 8632, 24564, 2172, 29166, 22153, 22365, 16356, 24800, 8049, 1541, 15294, 4511, 27730, 23546, 47665, 28297 }; int[] ordersOfAdmissionToFederation = new int[] { 2, 14, 5, 16, 18, 31, 28, 4, 3, 27, 12, 24, 29, 13, 9, 1, 21, 23, 10, 20, 25, 30, 15, 26, 22, 8, 11, 7, 6, 17, 19 }; DateTime[] dateOfAdmissionToFederation = new DateTime[] { new DateTime(1823, 12, 20), new DateTime(1824, 2, 7), new DateTime(1823, 12, 22), new DateTime(1824, 5, 7), new DateTime(1824, 7, 6), new DateTime(1952, 1, 16), new DateTime(1917, 1, 26), new DateTime(1823, 12, 21), new DateTime(1823, 12, 21), new DateTime(1869, 4, 17), new DateTime(1824, 1, 10), new DateTime(1857, 2, 5), new DateTime(1952, 1, 16), new DateTime(1824, 2, 7), new DateTime(1823, 12, 23), new DateTime(1823, 12, 20), new DateTime(1849, 10, 27), new DateTime(1856, 9, 12), new DateTime(1823, 12, 23), new DateTime(1830, 10, 14), new DateTime(1863, 4, 29), new DateTime(1974, 10, 8), new DateTime(1824, 5, 7), new DateTime(1869, 1, 16), new DateTime(1856, 12, 9), new DateTime(1823, 12, 23), new DateTime(1823, 12, 23), new DateTime(1823, 12, 22), new DateTime(1823, 12, 22), new DateTime(1824, 5, 22), new DateTime(1824, 9, 14) }; ListViewItem lviState = null; for (int i = 0; i < states.Length; i++) { lviState = new ListViewItem((i + 1).ToString()); lviState.SubItems.Add(states[i]); lviState.SubItems.Add(areasSqrKms[i].ToString()); lviState.SubItems.Add(areasSqrMiles[i].ToString()); lviState.SubItems.Add(dateOfAdmissionToFederation[i].ToString()); lviState.SubItems.Add(ordersOfAdmissionToFederation[i].ToString()); lviState.SubItems.Add(capitals[i].ToString()); lvwDepreciation.Items.Add(lviState); } } } }
Introduction to the Characteristics of a Date Value
Introduction
The pieces of information of the DateTime structure are:
The Default Date Values
The default constructor of the DateTime structure initializes the date to January 1st, 0001 and the time at midnight (01:01:01). Here is an example that shows it:
using System; using static System.Console; public class Exercise { public static int Main(string[] args) { DateTime tm = new DateTime(); Title = "Date and Time Values"; WriteLine("Default date and time: {0}", tm); WriteLine("==========================================="); return 3; } }
This would produce:
Default date and time: 1/1/0001 12:00:00 AM =========================================== Press any key to continue . . .
The Minimum Date Value
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 Maximum Date Value
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 Date a Value
As done with the regular numbers, you can request a date value from the user. To support this operation, the DateTime structure is equipped with the same Parse method that we reviewed for the other structures of the C# data type. This method is overloaded. The simplest version uses the following syntax:
public static DateTime Parse (string s);
To use this method, pass a string that may contain a date, a time, or a date/time value. On a console application, you can pass a Console.Read() or a Console.ReadLine() method. Here is an example:
using System; using static System.Console; public class Exercise { public static int Main(string[] args) { DateTime dtDateHired = new DateTime(); Title = "Human Resources"; Write("Enter Date Hired: "); dtDateHired = DateTime.Parse(ReadLine()); WriteLine("Date Hired: {0}", dtDateHired); WriteLine("==========================================="); return 3; } }
In the same way, if you aske this method, pass a string that may contain a date, a time, or a date/time value. On a console application, you can pass a Console.Read() or a Console.ReadLine() method. Here is an example:
using System; using static System.Console; public class Exercise { public static int Main(string[] args) { DateTime dtDateHired = new DateTime(); Title = "Human Resources"; Write("Enter Date Hired: "); dtDateHired = DateTime.Parse(ReadLine()); WriteLine("Date Hired: {0}", dtDateHired); WriteLine("==========================================="); return 4; } }
After the user has entered a string in a text box, 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 webserver may throw an exception. 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.
Dates Parts
Introduction to Rules of Date Formats
The computer uses two main categories to display dates using specific characters to represent its value.
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;
using static System.Console;
public class Exercise
{
public static int Main(string[] args)
{
DateTime date = new DateTime(2002, 4, 22);
string strMonth = date.ToString("MM");
Title = "Dates Characteristics";
WriteLine("Date and Time: {0}", date);
WriteLine("Month Value: {0}", strMonth);
WriteLine("===========================================");
return 3;
}
}
This would produce:
Date and Time: 4/22/2002 12:00:00 AM Month Value: 04 =========================================== Press any key to continue . . .
If 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;
using static System.Console;
public class Exercise
{
public static int Main(string[] args)
{
Title = "Dates Characteristics";
DateTime date = new DateTime(1998, 1, 12);
string strMonth = date.ToString("MMM");
WriteLine("Date and Time: {0}", date);
WriteLine("Month Name: {0}", strMonth);
WriteLine("===========================================");
return 4;
}
}
This would display:
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;
using static System.Console;
public class Exercise
{
public static int Main(string[] args)
{
Title = "Dates Characteristics";
DateTime date = new DateTime(2004, 10, 23);
string strMonth = date.ToString("MMMM");
WriteLine("Date and Time: {0}", date);
WriteLine("Month Name: {0}", strMonth);
WriteLine("===========================================");
return 5;
}
}
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;
using static System.Console;
public class Exercise
{
public static int Main(string[] args)
{
Title = "Dates Characteristics";
DateTime date = new DateTime(2002, 4, 2);
string strDay = date.ToString("dd");
WriteLine("Date and Time: {0}", date);
WriteLine("Month Value: {0}", strDay);
WriteLine("===========================================");
return 6;
}
}
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;
using static System.Console;
public class Exercise
{
public static int Main(string[] args)
{
Title = "Dates Characteristics";
DateTime date = new DateTime(2002, 4, 2);
string strYear2Digits = date.ToString("yy");
WriteLine("Date and Time: {0}", date);
WriteLine("Year Value: {0}", strYear2Digits);
WriteLine("===========================================");
return 7;
}
}
This would display:
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; using static System.Console; public class Exercise { public static int Main(string[] args) { Title = "Dates Characteristics"; DateTime date = new DateTime(2002, 4, 2); string strYear4Digits = date.ToString("yyyy"); WriteLine("Date and Time: {0}", date); WriteLine("Year Value: {0}", strYear4Digits); WriteLine("==========================================="); return 8; } }
This would display:
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; using static System.Console; public class Exercise { public static int Main(string[] args) { Title = "Dates Characteristics"; DateTime date = new DateTime(98, 4, 2); string strYear4Digits = date.ToString("yyyy"); WriteLine("Date and Time: {0}", date); WriteLine("Year Value: {0}", strYear4Digits); WriteLine("==========================================="); return 9; } }
This would display:
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
Getting a Date Value From a DateTime Object
You may have noticed 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:
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.
The 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:
Don't pass the forward slash by itself to the ToString() method.
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; using static System.Console; public class Exercise { public static int Main(string[] args) { Title = "Dates Characteristics"; DateTime date = new DateTime(2004, 10, 23); WriteLine("Date Value: {0}", date.ToString("M/d/yyyy")); WriteLine("Date Value: {0}", date.ToString("M/d/yy")); WriteLine("Date Value: {0}", date.ToString("MM/dd/yy")); WriteLine("Date Value: {0}", date.ToString("MM/dd/yyyy")); WriteLine("Date Value: {0}", date.ToString("yy/MM/dd")); WriteLine("Date Value: {0}", date.ToString("yyyy-MM-dd")); WriteLine("Date Value: {0}", date.ToString("dd-MMM-yy")); WriteLine("================================="); return 8; } }
This would produce:
Date Value: 10/23/2004 Date Value: 10/23/04 Date Value: 10/23/04 Date Value: 10/23/2004 Date Value: 04/10/23 Date Value: 2004-10-23 Date Value: 23-Oct-04 ================================= Press any key to continue . . .
Practical Learning: Formatting a Date Value
uusing System;
using System.Windows.Forms;
namespace CountriesStatistics4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Present();
}
void Present()
{
string[] states = new string[31];
. . .
ListViewItem lviState = null;
for (int i = 0; i < states.Length; i++)
{
lviState = new ListViewItem((i + 1).ToString());
lviState.SubItems.Add(states[i]);
lviState.SubItems.Add(areasSqrKms[i].ToString());
lviState.SubItems.Add(areasSqrMiles[i].ToString());
lviState.SubItems.Add(dateOfAdmissionToFederation[i].ToString("M/d/yyyy"));
lviState.SubItems.Add(ordersOfAdmissionToFederation[i].ToString());
lviState.SubItems.Add(capitals[i].ToString());
lvwStates.Items.Add(lviState);
}
}
}
}
The Short 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. To support short dates, the DateTime structure is equipped with a method named ToShortDateString. Its syntax is:
public string ToShortDateString();
As another option to get a short date, on a DateTime value, pass a "d" (one d in lowercase) string to the ToString() method. Here is an example:
using System;
using static System.Console;
public class Exercise
{
public static int Main(string[] args)
{
Title = "Dates Characteristics";
DateTime date = new DateTime(2004, 10, 23);
string strDate = date.ToString("d");
WriteLine("Date and Time: {0}", date);
WriteLine("Date Portion: {0}", strDate);
WriteLine("=====================================");
return 9;
}
}
This would produce:
Date and Time: 10/23/2004 12:00:00 AM Date Portion: 10/23/2004 ===================================== Press any key to continue . . .
The Long Date Format
A date is referred to as long if it includes the names of the month and of the day of the week of a date value. This is called the Long Date Format. To let you get the Long Date of a date, the DateTime structure is equipped with a method named ToLongDateString, Its syntax is:
public string ToLongDateString ();
As another way to get a long date, pass a "D" (one d in uppercase) string to the ToString() method of a DateTime value. Here is an example:
using System;
using static System.Console;
public class Exercise
{
public static int Main(string[] args)
{
Title = "Dates Characteristics";
DateTime date = new DateTime(2004, 10, 23);
string strDate = date.ToString("D");
WriteLine("Date and Time: {0}", date);
WriteLine("Date Portion: {0}", strDate);
WriteLine("===========================================");
return 8;
}
}
This 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;
using static System.Console;
public class Exercise
{
public static int Main(string[] args)
{
Title = "Dates Characteristics";
DateTime date = new DateTime(2004, 10, 23);
string strDate = date.ToString("M");
WriteLine("Date and Time: {0}", date);
WriteLine("Month and Year: {0}", strDate);
WriteLine("=======================================");
return 9;
}
}
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;
using static System.Console;
public class Exercise
{
public static int Main(string[] args)
{
Title = "Dates Characteristics";
DateTime date = new DateTime(2004, 10, 23);
string strDate = date.ToString("y");
WriteLine("Date and Time: {0}", date);
WriteLine("Month and Year: {0}", strDate);
WriteLine("=======================================");
return 10;
}
}
This would produce:
Date and Time: 10/23/2004 12:00:00 AM Month and Year: October, 2004 ======================================= Press any key to continue . . .
Practical Learning: Ending the Lesson
|
||
Previous | Copyright © 2001-2020, FunctionX | Next |
|