Dates and Times |
|
Dates and Times |
Introduction |
A date is a measure of non-spatial units that have elapsed in a set period. To perform this measure, a certain point is set and called midnight. From that point, a number of units are counted until the next corresponding point is reached. Because the light in daily life changes from one midnight unit to the next midnight unit, the sub-point when the light shows up, or starts, is called sunrise. The sub-point when the light diminishes or starts disappearing is called sunset. The midpoint between the sunrise and the sunset is called noon. The first part, from midnight to noon is referred to as AM in US English. The other part is referred to as PM in US English. |
The group of units between two midnight points is called a day. The days are counted from 0, 1, and up. A group of seven consecutive days is called a week. The weeks are counted from 1 and up. To make it easy to identify a day, the days of a week are named as Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, and Sunday. These are referred to as long names. The corresponding short names are Mon, Tue, Wed, Thu, Fri, Sat, and Sun. The day considered as the first of the week depends on the language and/or some other considerations. For example, in US English, Sunday is usually considered the first day of the week. |
Most of the time, a group of four weeks is called a month. The months are counted from 1 and up. To make it easy to identify a month, each holds a long name and they are January, February, March, April, May, June, July, August, September, October, November, and December. Their short names are Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, and Dec. Except for the month of February that depends on a factor named Leap Year, the maximum days of each month are January=31, March=31, April=30, May=31, June=30, July=31, August=31, September=30, October=31, November=30, and December=31. A group of three months is called a trimester. A group of four months is called a quarter. A group of six months is called a semester. A group of twelve months is called a year. The years are counted from 1 and up (some compilers or applications specify when the years start; for example, some applications start their count at 1901 and cannot process years below that numbers; some other applications would not process a year beyond a certain year). The .NET Framework compilers count the years from 0001 to 9999. In a regular year, the months are counted from 1 to 12. The technique or expression used to identify a particular day during a year is called a date. The days are counted from 1 to 365 or 366 (depending on a factor called a leap year). A date can be the combination of a day, its months, and the year. There are other aspects that can be taken into consideration. We will address them when necessary. A unit of measure in a day is called a second. The seconds are counted from 0 to 59 or from 0, 1, 2, and so on. In some applications, when precision is particularly important, a second is considered a group of 1000 portions called milliseconds. The milliseconds are counted from 0 to 999. A group of 60 seconds is called a minute. A group of 60 minutes is called an hour. A group of 24 hours is called a day. The technique or expression used to identify a particular unit of measure during a day is called the time. It can be the combination of the hour, the minute, and the second. Some other aspects may be taken into consideration. We will review them as we move on.
To represent the dates, computers, applications, and compilers are configured with specific techniques. In Microsoft Windows, to manage dates, the operating system provides a structure named SYSTEMTIME. To manage dates, the .NET Framework provides the DateTime structure. To create a date or a time value, you can first declare DateTime variable. To assist you with initializing the variable, the DateTime structure is equipped with various constructors. The default constructor allows you to create a date or a time object without specifying its details. This would be done as follows: using System; namespace DateAndTime { class Program { static int Main() { DateTime tm = new DateTime(); return 0; } } } After declaring a DateTime variable and initializing it, it holds all necessary pieces of information about its date and its time values.
You can access the information using the variable. The pieces of information are represented by properties of the DateTime structure and they are:
The default constructor of the DateTime structure initializes the date to January 1st, 0001 and the time at midnight (01:01:01). This is illustrated in the following program: using System; namespace DateAndTime { class Program { static int Main() { DateTime tm = new DateTime(); Console.WriteLine("Default Date and Time: {0}", tm); return 0; } } } This would produce: Default Date and Time: 1/1/0001 12:00:00 AM Press any key to continue . . . This also means that the lowest date and time values that a DateTime object can hold is January 1st, 0001 at 00:00:00. This value is represented by the MinValue constant member of the DateTime structure. The highest date and time that a DateTime object can hold in the structure is called MaxValue and it is set at December 31, 9999.
A date is a technique of identifying a period using three numbers: the year, the month, and the day. Each is an integer value. If you know the values you want to use to create or specify a date value, when declaring a DateTime variable, you can use the following constructor: public DateTime(int year, int month, int second); Here is an example of creating a date: using System; namespace DateAndTime { class Program { static int Main() { DateTime ind = new DateTime(1960, 1, 1); Console.WriteLine("Independence Day: {0}", ind); return 0; } } } This would produce: Independence Day: 1/1/1960 12:00:00 AM Press any key to continue . . .
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.
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:
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.
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:
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 . . .
Instead of creating your own format, the Microsoft Windows operating system provides two names that can be used to identify a date. A date is referred to as short if it includes (only) the numeric portions of the month and the day of a date value. The operating systems follows the rules we have reviewed so far for the numbers and the Date Separator. The possible formats of a short date can be seen in the Short Date Format combo box of the Date tab of the Customize Regional Options of the Regional and Language Settings of the Control Panel:
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 . . .
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:
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 . . .
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 . . . |
One of the operations performed on date values is to find out whether the year value of a date is a leap year. Fortunately, the static IsLeapYear() method of the DateTime structure can be used to perform this operation. The syntax of this function is: public static bool IsLeapYear(int year); This method takes an integer argument and examines it. If the argument, which must be a valid year number, is a leap year, the method returns true; otherwise, it would return false. Here are two examples: using System; namespace DateAndTime { class Program { static int Main() { DateTime date = new DateTime(1988, 10, 6); Console.WriteLine("{0} was a leap year: {1}", date.Year, DateTime.IsLeapYear(date.Year)); date = new DateTime(1990, 8, 12); Console.WriteLine("{0} was a leap year: {1}", date.Year, DateTime.IsLeapYear(date.Year)); return 0; } } } This would produce: 1988 was a leap year: True 1990 was a leap year: False Press any key to continue . . .
The DateTime structure is equipped with a property that can be used to retrieve the day of the week for a given date. The property is named DayOfWeek. To get the day of the week, access the DayOfWeek property a your DateTime value or variable. The values are stored in the DayOfWeek enumeration. Here is an example: using System; namespace DateAndTime { class Program { static int Main() { DateTime date = new DateTime(1988, 10, 6); Console.WriteLine("Day of the week: {0}", date.DayOfWeek); return 0; } } } This would produce: Day of the week: Thursday Press any key to continue . . .
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.
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.
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.
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.
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 . . .
As defined earlier, the time is a value used to identify the number of units that have elapsed since a starting period, called midnight, of a day. A day is made of 24 non-spatial divisions; each one of these divisions is called an hour. An hour is made of 60 fractions and each one of these fractions is called a minute. A minute is divided in 60 parts, each called a second. As done with dates, most of the operations performed on time values are centered around the DateTime structure. The rules used by the computer for time display can be seen in the Customize Regional Options dialog box. To access it, in the Control Panel, you can double-click Regional and Language Options. In the Regional Options tab of the Regional and Language Options dialog box, you can click Customize. In the Customize Regional Options, you can click Time:
In US English, the symbol to separate the hour and the minute. An example would be: 08:25. In the same way, in US English, the character used to separate the minute and the second is “:”. An example would be: 08:25:44. In many cases, unless necessary, the second is not represented in a time value. The time of a day can be considered as a value of 24 hours or the day can be considered as two fractions of 12 hours each. There is a period in the middle of day time called noon. It divides the 24-hour day in two parts, each consisting of 12 hours. The noon period is positioned 12 hours after midnight. The period that goes from midnight to the middle of day time is represented by the expression AM. The period from noon to midnight is represented by the PM expression. When a DateTime object includes an AM or PM but of unknown value, the section is represented as AM/PM and this expression is written on the right side of the seconds. To separate the seconds and the AM/PM, you (as well as the compiler) leave a one-character empty space after the seconds.
The time portion of a DateTime structure can be declared and manipulated as a value. To create a time value, you can declare a DateTime variable using the following constructor: public DateTime(int year, int month, int day, int hour, int minute, int second); If you are more concerned about the time, the first, second, and third arguments are not important. You can pass each as 1. In this case, the date would be set as January 1, 0001. The other three arguments represent the components of a time value. The minutes value must range from 0 to 59; otherwise, an error would be produced (when studying exception handling, we will see that this means that the compiler would throw an exception). The seconds value must be between 0 and 59 or the program would cause an error. When initializing a date or time variable using this constructor, the hour value must be between 0 and 23. Any other value outside of this range will cause an error. If the hour portion has a value between 0 and 11, the time is set in the morning with the AM in the AM/PM section. Here is an example: using System; namespace DateAndTime { class Program { static int Main() { DateTime time = new DateTime(1, 1, 1, 10, 24, 52); Console.WriteLine("Time: {0}\n", time); return 0; } } } This would produce: Time: 1/1/0001 10:24:52 AM Press any key to continue . . . If the hour portion is between 12 and 23, the time is set in the afternoon. When displaying it, the compiler, by default, calculates and displays the 0 to 12 portion and then displays PM in the AM/PM section. Here is an example: using System; namespace DateAndTime { class Program { static int Main() { DateTime time = new DateTime(1, 1, 1, 16, 8, 44); Console.WriteLine("Time: {0}\n", time); return 0; } } } This would produce: Time: 1/1/0001 4:08:44 PM Press any key to continue . . . In extreme cases, you may want to use the milliseconds of a time value. When declaring and initializing the variable, you can use the following constructor: public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond); The milliseconds must range from 0 to 999. If you do not know the millisecond value, you can provide it as 0.
In a certain application, you may want the user to supply a time value. As mentioned for the date, there are rules that you, the computer, and the user must follow to apply a valid formula. As mentioned earlier, the compiler refers to the computer to find out what a date looks like. A valid time can follow the format hh:nn AM/PM or hh:nn:ss or one of the valid combinations. When requesting a time from the user, in case the user is not familiar with the rules (and you should assume that the user doesn't know them), specify what formula the user should follow. Here is an example: using System; namespace DateAndTime { class Program { static int Main() { DateTime dateSubmitted; Console.Write("Enter a date (yyyy/mm/dd): "); dateSubmitted = DateTime.Parse(Console.ReadLine()); Console.WriteLine("\nDate Submitted: {0}\n", dateSubmitted); return 0; } } } Here is an example of running the program: Enter a date (yyyy/mm/dd): 1996/08/16 Date Submitted: 8/16/1996 12:00:00 AM Press any key to continue . . .
By now, we have seen that a time value is made of the hour, the minute, the second, and the millisecond parts. These are values you can specify when creating a time object using one of the appropriate constructors of the DateTime structure. If you request a time value from the user or if the application itself will provide it, you can retrieve its components. To get the hour portion of an existing DateTime object, you can access its Hour property. To retrieve the minute side of a time value, access its Minute property. If you want to know the second value of a DateTime variable, you can call its Second property. In the same way, you can get the millisecond value of a time by accessing its Millisecond property.
As seen so far, a DateTime variable always holds both a date and a time portions. In your program, you may want to get only the time of the variable. To support this, the DateTime structure is equipped with a property named TimeOfDay. This property produces the time value of an existing DateTime object. Here is an example of using it: using System; namespace DateAndTime { class Program { static int Main() { DateTime time = new DateTime(2002, 4, 22, 16, 8, 44); Console.WriteLine("Date and Time: {0}\n", time); Console.WriteLine("Time of Day: {0}\n", time.TimeOfDay); return 0; } } } This would produce: Date and Time: 4/22/2002 4:08:44 PM Time of Day: 16:08:44 Press any key to continue . . .
If you have a DateTime object, you can convert it to a String value. To make this operation possible, the DateTime structure is equipped with a method named ToString. The default version of this method takes no argument and it simply creates a string out of a time value. Here is an example: using System; namespace DateAndTime { class Program { static int Main() { DateTime time = new DateTime(2002, 4, 22, 16, 8, 44); string strTime = time.ToString(); Console.WriteLine("Date and Time(DateTime): {0}\n", time); Console.WriteLine("Date and Time(String): {0}\n", strTime); return 0; } } } This would produce: Date and Time(DateTime): 4/22/2002 4:08:44 PM Date and Time(String): 4/22/2002 4:08:44 PM Press any key to continue . . . Notice that the value produced by the string includes both the date, the time and even the AM/PM section. In some cases, you would be interested only in either the date or the time. To support this type of operation, the DateTime structure has another overloaded version of the ToString() method that takes as argument a String value. Its syntax is: public string ToString(string format); When calling this method, there are rules you should/must follow.
Like dates, time values follow the Regional (and Language) Settings of Control Panel when they display. To make this display friendlier, Microsoft Windows provides the rules, through some characters, you can use to format a time:
The characters used to create a format are:
To create or format a (complete) time value, you must use a combination of characters:
When combining these characters to create a format, you should abide by the rules of your language, such as US English. You should refer to the formula set in the Time property page of the Regional (and Language) Settings of Control Panel.
As done for date values, you can compare time values to find out if one occurs before another or whether they occur at the same time. To support the comparisons, the DateTime structure is equipped with the Compare() method.
When a user starts a computer and while using it, it keeps a date and time values referred to as local date and time or system date and time. Depending on your application, at one time you may need to get one or both of these pieces of information. It is important to know that the computer, not you, controls this information (but you can programmatically change it if you want). To support both, the DateTime structure is equipped with a static property named Now. This property holds the year, the month, the day, the name of the day, the hour, the minute, and the second. Here is an example of calling it: using System; namespace DateAndTime { class Program { static int Main() { Console.WriteLine("System Date and Time: {0}", DateTime.Now); return 0; } } } Here is an example of running the program: System Date and Time: 10/15/2006 3:08:48 PM Press any key to continue . . . To get the current date of the computer, the DateTime structure provides a static property named Today. Here is an example: using System; namespace DateAndTime { class Program { static int Main() { Console.WriteLine("Current Date: {0}", DateTime.Today); return 0; } } } Here is an example of running the program: Current Date: 10/15/2006 12:00:00 AM Press any key to continue . . .
Although the DateTime structure is equipped to produce default values of a date and time in combination, you can use the formats we have reviewed to create your own date, in the sequences of your choice, such as a time preceding a date, a value providing only the month and the minutes, etc. |
|
||
Previous | Copyright © 2008-2016, FunctionX, Inc. | Next |
|