Topics on Date and Time Values
Topics on Date and Time Values
Time Fundamentals
Introduction
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. A time is a value to identify the number of units that have elapsed since midnight of a day.
The rules used by the computer for time display can be seen in the Customize Regional Options dialog box:
Creating a Time Value
To support time values, the .NET library provides a structure named TimeOnly. Therefore, you can declare a variable of that type. To allow you to initiate a time value, the TimeOnly structure is equipped with five constructors. The default constructor allows you to create a simple time value. Here is an example:
@{
TimeOnly toStart = new TimeOnly();
}
Accessing a Time Value
After creating a TimeOnly object, you can access it. If you are working in a razor page, you can write @, followed by the name of the TimeOnly variable. Include the expression in an HTML tag. Here is an example:
@page @model Valuable.Pages.TimesValuesModel @using static System.Console @{ TimeOnly to = new TimeOnly(); WriteLine("Default Time: {0}", to); } <h3>Times Characteristics</h3> <pre>Default Time: @to =================================</pre>
This would produce:
Times Characteristics Default Time: 12:00 AM =================================
Populating a Time Value
A Time for an Hour and Minute
The primary components of a time value are the hour and the minute. In fact, when we communicate teh time to someone, we usually give only the hourly and the minute. To allow you to provide time with those values, the TimeOnly structure is equipped with the following constructor:
public TimeOnly(int hour, int minute);
This construtor takes two arguments. The first argument, for the hour, is one of 24 parts of a day. The value must be an integer between 0 and 23. The second argument, for the minute, is one of 60 parts of an hour. It is a value between 0 and 59. If you pass a value out of those ranges, when you compile the project, the program would produce an exception.
Filling the Three Values of a Time Object
The classic components of a time value are the hour, the minute, and the second. The second is one of 60 parts of a minute. To allow you to create a time object with these three values, the TimeOnly structure is equipped with an appropriate constructor. Its syntax is:
public TimeOnly(int hour, int minute, int second);
When using this constructor, pass the appropriate integral values. The third argument, for the seconds, holds a value between 0 and 59. Here is an example that uses this constructor:
@page
@model Exercise.Pages.ExerciseModel
@{
TimeOnly time = new TimeOnly(10, 24, 52);
}
<h3>Times Characteristics</h3>
<pre>Time: @time
=================================</pre>
The Milliseconds of a Date/Time Value
So far, we have seen that a time object contains the hour, the minutes, and the seconds. Some operations require more precision with a value that is a fraction of a second. Such a value is called a millisecond. A millisecond is 1000th of a second. It is a value between 0 and 999. To let you create a time object that specifies the milliseconds, the TimeOnly structure is equipped with the following constructor:
public TimeOnly(int hour, int minute, int second, int millisecond);
If you use this constructor to create a time object, pass a fourth argument as a value between 0 and 999.
A Tick-Based Value
A tick is a 100th portion of a second. This means that a certain number of ticks occurs during a day. One way to provide a time value is to specify the number of ticks that have occurred since midnight of a certain day. To support this, the TimeOnly structure is equipped with a constructor that takes a long integer as argument. Its syntax is:
public TimeOnly(long ticks);
A Combination of Date and Time
Introduction
As we have learned so far, a year is made of 365 or 12 months. A month is made of 28, 29, 30, or 31 days. A day in divived in 24 hours. An hour is made of 60 minutes, and a minute contains 60 seconds. So far, we used separate objects for either a date or a time. In some cases, you may want to consider all these values as one. To support this, the .NET library provides a structure named type DateTime.
A Date Object
In the previous lesson, we saw that, to create a simple date value, we could declare a type DateOnly variable. To support this, the DateTime structure is equipped with the following constructor:
public DateTime(int year, int month, int day);
This constructor takes the arguments exactly as we described for the DateOnly structure.
An Object with a Date and Time
Probably the most common way to provide a complete day is to specify the values for the day, the month, the day, the hour, the minutes, and the seconds. To allow you to provide all these pieces of information, the DateTime structure is equipped with constructor that takes six arguments. Its syntax is:
public DateTime(int year, int month, int day, int hour, int minute, int second);
To create a complete date date using this constructor, declare a DateTime variable and pass the arguments in the right order and the value of each argument must be in the appropriate range. If you need to specify the milliseconds of a date/time value, use the following constructor:
public DateTime(int year, int month, int day,
int hour, int minute, int second, int millisecond);
Requesting a Date/Time Value
In a certain application, you may want the visitor to provide a time value. A valid time can follow the format hh:nn AM/PM or hh:nn:ss or one of the valid combinations. When creating an application that needs a date and time, you simply provide a text box and trust that the user would type a valid value. To assist you, you can add an input control to your HTML form. To make it a date/time control, set its type as datetime.
Characteristics of a Date/Time Value
The Time Separator
In US English, the symbol to separate the hour and the minute is the colon ":". An example is 08:25. The character used to separate the minutes and the seconds is the colon ":". An example would be: 08:25:44. In many cases, unless necessary, the second is not represented in a time value. Consider the following example:
@page @model Valuable.Pages.TimesValuesModel @using static System.Console @{ DateTime time = new DateTime(1, 1, 1, 16, 8, 44); WriteLine("Time: {0}", time); } <h3>Times Characteristics</h3> <pre>Time: @time =================================</pre>
This would produce (notice the colons separators in the time value):
Times Characteristics Time: 1/1/0001 4:08:44 PM =================================
The AM/PM Factor
A day is considered in two parts referred to as morning or before noon and afternoon. You can keep this in mind when specify the parts of a time value. For example, when declaring a DateTime variable, if the hour portion is between 12 and 23, the time is set in the afternoon. Here is an example:
@page
@model Exercise.Pages.ExerciseModel
@{
DateTime time = new DateTime(1, 1, 1, 16, 8, 44);
}
<pre>Time: @time
=================================</pre>
This would produce:
Time: 1/1/0001 4:08:44 PM =================================
The Time of Day of a DateTime Value
As seen so far, a DateTime variable always holds both a date and a time portions. In your design, 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:
@page @model Exercise.Pages.ExerciseModel @{ DateTime time = new DateTime(2022, 4, 22, 16, 8, 44); WriteLine("Date and Time: {0}", time); WriteLine("Time of Day: {0}", time.TimeOfDay); } <h3>Times Characteristics</h3> <pre>Date and Time: @time Time of Day: @time.TimeOfDay ===================================</pre>
This would produce:
Date and Time: 4/22/2022 4:08:44 PM Time of Day: 16:08:44 ===================================
The Current Date and Time
When a user starts a computer and while using it, it keeps a date and time values referred to as local date and time or system date and time. Depending on your application, at one time you may need to get one or both of these pieces of information. It is important to know that the computer, not you, controls this information (but you can programmatically change it if you want). To support both, the DateTime structure is equipped with a static property named Now. This property holds the year, the month, the day, the name of the day, the hour, the minute, and the second. Here is an example of accessing it:
@page
@model Exercise.Pages.ExerciseModel
@using static System.Console
@{
WriteLine("Date and Time Values");
WriteLine(string.Format("System Date and Time: {0}", DateTime.Now));
WriteLine("============================================");
}
Here is an example of running the program:
System Date and Time: 9/10/2020 10:18:41 PM ============================================
To get the current date of the computer, the DateTime structure provides a static property named Today. Here is an example:
@page
@model Exercise.Pages.ExerciseModel
@{
WriteLine("Date and Time Values");
WriteLine(string.Format("Current Date: {0}", DateTime.Today));
WriteLine("====================================");
}
Here is an example of running the program:
Current Date: 9/10/2020 12:00:00 AM ====================================
The Leap Year
A leap year is a year in which the month of February has 29 days. To let you find out whether a year is a leap year, the DateTime structure is equipped with a static method named IsLeapYear. The syntax of this method 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 returns false. Here are two examples:
@page @model Exercise.Pages.ExerciseModel @{ DateTime date1 = new DateTime(1988, 10, 6); DateTime date2 = new DateTime(1990, 8, 12); } <h3>Dates Characteristics</h3> <pre>@date1.Year was a leap year: @DateTime.IsLeapYear(date1.Year) @date2.Year was a leap year: @DateTime.IsLeapYear(date2.Year) =================================</pre>
This would produce:
1988 was a leap year: True 1990 was a leap year: False =================================
The Day of the Week
The DateTime structure is equipped with a property that can be used to retrieve the day of the week for a given date. The property is named DayOfWeek. To get the day of the week, access the DayOfWeek property a your DateTime value or variable. The values are stored in the DayOfWeek enumeration. Here is an example:
@page @model Exercise.Pages.ExerciseModel @{ DateTime date = new DateTime(1988, 10, 6); } <h3>Dates Characteristics</h3> <pre>Date and Time: @date Day of the week: @date.DayOfWeek ======================================</pre>
This would produce:
Date and Time: 10/6/1988 12:00:00 AM Day of the week: Thursday ======================================
Topics on Date/Time Values
Converting a Time Value to a String
If you have a DateTime object, you can convert it to a String value. To make this operation possible, as mentioned previously, tthe DateTime structure overrides the ToString() method. The default version of this method takes no argument and it simply creates a string out of a time value. Here is an example:
@page @model Exercise.Pages.ExerciseModel @{ DateTime time = new DateTime(2024, 4, 22, 16, 8, 44); string strTime = time.ToString(); } <h3>Times Characteristics</h3> <pre>Date and Time (DateTime): @time Date and Time (String): @strTime ===============================================</pre>
This would produce:
Date and Time (DateTime): 4/22/2024 4:08:44 PM Date and Time (String): 4/22/2024 4:08:44 PM ===============================================
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.
Introduction to Time Rules and Formats
Like dates, time values follow some rules:
Introduction to Formatting a Time Value
As mentioned already, a time value must use some pre-determined rules to be appropriately readable and interpreted. The rules include the use of some specific letters and symbols. The formats we will review can be used on a text-based value (console window, text box control, label, list-based controls, etc) presented to the user or on a Windows control (time picker, etc).
In our review, we will indicate some letters in uppercase or in lowercase. The format are somehow case-sensitive. This means that if you are are to use something like "hh" or "HH", don't use "Hh". Also, don't a a character inside of an indicated combination. This means that "hh" is not the same as "h h" or "h-h".
Formatting Date and Time Combinations
Although the DateTime structure is equipped to produce default values of a date and time in combination, you can use the formats we have reviewed to create your own date, in the sequences of your choice, such as a time preceding a date, a value providing only the month and the minutes, etc.
Hour Formats
Introduction
The h and the H are used for the hour values. Don't use the letter "h" or "H" by itself in a ToString() method. If you do, you will receive a FormatException exception.
hh
The "hh" combination is used for an hour number from 0 to 12 and the compiler must know if the time is happening in the morning or afternoon (including evening). If the hour is from midnight to noon, which is from 0 to 12, if the less than 10, it would display with the leading 0. Here is an example:
@page @model Exercise.Pages.ExerciseModel @{ DateTime time = new DateTime(2024, 4, 22, 5, 8, 37); string strHour = time.ToString("hh"); } <h3>Times Characteristics</h3> <pre>Date and Time: @time Hour Value: @strHour =====================================</pre>
This would produce:
Date and Time: 4/22/2024 5:08:37 AM Hour Value: 05 =====================================
If the hour occurs in the afternoon, im which case the hour value is greater than 12, such as 15, 12 would be subtract from it and it would display with a leading 0, such as 05. Here is an example:
@page @model Exercise.Pages.ExerciseModel @{ DateTime time = new DateTime(2024, 4, 22, 15, 8, 37); string strHour = time.ToString("hh"); } <h3>Times Characteristics</h3> <pre>Date and Time: @time Hour Value: @strHour =====================================</pre>
This would produce:
Date and Time: 4/22/2024 3:08:37 PM Hour Value: 03 =====================================
HH
The HH expression is used for an hour number from 0 to 23. If the hour is less than 10, it would display with the leading 0. The effect is the same as seen for the hh format. If the hour is greater than 12, such as 15, it would display with that value. Here is an example:
@page @model Exercise.Pages.ExerciseModel @{ DateTime time = new DateTime(2024, 4, 22, 15, 8, 37); string strHour = time.ToString("HH"); } <h3>Times Characteristics</h3> <pre>Date and Time: @time Hour Value: @strHour =====================================</pre>
This would produce:
Date and Time: 4/22/2024 3:08:37 PM Hour Value: 15 =====================================
Minute Formats
mm
The mm combination is used for minutes. A minute is a number from 0 to 59. If the number is less than 10, it would display with the leading 0 such as 06. Here is an example:
@page @model Exercise.Pages.ExerciseModel @{ DateTime time = new DateTime(2024, 4, 22, 15, 8, 37); string strMinute = time.ToString("mm"); } <h3>Times Characteristics</h3> <pre>Date and Time: @time Minute Value: @strMinute); =====================================</pre>
This would display:
Date and Time: 4/22/2024 3:08:37 PM Minute Value: 08 =====================================
If the number is greater than 9, it would display the same.
The Time Separator :
To express a time value, you use some letters or a combination of some letters and some symbols. If you use a combination of letters and symbols, you must use some specific symbols. For example, the letters must be separated by some specific symbols. The character used to separate the parts of a date is set in the Regional (and Language) Settings of Control Panel. In US English, this character is the colon (:). Don't pass that character by itself to the ToString() method.
m
The letter m is used to format the minutes. This letter can be combined to the h letters used for the hour. In this case, the letter m would follow the letter h after a time separator, as in h:m.
A minute is a number from 0 to 59. If the number is less than 10, it would display without the leading 0. Here is an example:
@page @model Exercise.Pages.ExerciseModel @{ DateTime time = new DateTime(2024, 4, 22, 15, 8, 37); string strMinute = time.ToString("h:m"); } <h3>Times Characteristics</h3> <pre>Date and Time: @time Minute Value: @strMinute =====================================</pre>
This would display:
Date and Time: 4/22/2024 3:08:37 PM Minute Value: 3:8 =====================================
If the minute number is greater than 9, it would display as such. Don't use the letter "m" by itself in a ToString() method.
You can also use variants of the h and m letters to create an expression that will display the time in a format of your choice. Here are examples:
@page @model Exercise.Pages.ExerciseModel @using static System.Console @{ WriteLine("Times Characteristics"); DateTime time = new DateTime(2024, 4, 22, 5, 8, 37); string strMinute1 = time.ToString("h:m"); string strMinute2 = time.ToString("hh:m"); string strMinute3 = time.ToString("h:mm"); string strMinute4 = time.ToString("hh:mm"); WriteLine("Date and Time: {0}", time"); WriteLine("Time Value: {0}", strMinute1); WriteLine(string.Format("Time Value: {0}", strMinute2)); WriteLine($"Time Value: {strMinute3}"); WriteLine($"Time Value: {strMinute4}"); WriteLine("====================================="); }
This would display:
Date and Time: 4/22/2024 5:08:37 AM Time Value: 5:8 Time Value: 05:8 Time Value: 5:08 Time Value: 05:08 =====================================
Seconds Formats
ss
The ss combination is used for seconds. A second value from 0 to 59. If the number is less than 10, it would display with the leading 0 such as 04. Here is an example:
@page @model Exercise.Pages.ExerciseModel @{ DateTime time = new DateTime(2024, 4, 22, 15, 8, 7); string strSecond = time.ToString("ss"); } <h3>Times Characteristics</h3> <pre>Date and Time: @time Hour Value: @strSecond =====================================</pre>
This would display:
Date and Time: 4/22/2024 3:08:07 PM Hour Value: 07 =====================================
If the number is greater than 9, it would display like that.
Involving Seconds in a Time Value
One way to display a complete time time is to add the parts for the seconds to a combination of the hour(s) and minute(s). This is done by following the minutes part with a time separator and the s format.
The s letter is used to show the seconds of a time value. A second is a value from 0 to 59. If the number is less than 10, it would display without a leading 0. Here is an example:
@page @model Exercise.Pages.ExerciseModel @{ DateTime time = new DateTime(2024, 4, 22, 15, 8, 7); string strSecond = time.ToString("h:mm:s"); } <h3>Times Characteristics</h3> <pre>Date and Time: @time Second Value: @strSecond =====================================</pre>
This would display:
Date and Time: 4/22/2024 3:08:07 PM Second Value: 3:08:7 =====================================
The ss combination is used for seconds. A second is a value from 0 to 59. If the number is less than 10, it would display with a leading 0. Here is an example:
@page @model Exercise.Pages.ExerciseModel @{ DateTime time = new DateTime(2024, 4, 22, 15, 8, 7); string strSecond = time.ToString("h:mm:ss"); } <h3>Times Characteristics</h3> <pre>Date and Time: @time Second Value: @strSecond =====================================</pre>
This would display:
Date and Time: 4/22/2024 3:08:07 PM Second Value: 3:08:07 =====================================
tt or tttt
The tt and the tttt combinations are used for the AM/PM period. This means that the tt and tttt expressions are used to produce the AM or PM side of a time value. Here is an example:
@page
@model Exercise.Pages.ExerciseModel
@{
DateTime time = new DateTime(2024, 4, 22, 5, 8, 7);
string strAMPM = time.ToString("tt");
}
<h3>Times Characteristics</h3>
<pre>Date and Time: @time
AM/PM Side: @strAMPM
=====================================</pre>
This would display:
Date and Time: 4/22/2024 5:08:07 AM AM/PM Side: AM =====================================
Introduction to Dates Operations
A Time Span
Common operations on dates include adding days to a date, subtracting months from a date, adding years, comparing dates to find out whether one occurs before another, 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 provides a structure named TimeSpan. 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 Days to a Date Value
With the DateTime structure, you can add some days to an existing date. To support this, the DateTime structure is equipped with a method named AddDays. Its syntax is:
public DateTime AddDays(int days);
Here is an example of calling this method:
@page
@model Exercise.Pages.ExerciseModel
@{
DateTime startDate = new DateTime(1988, 10, 6);
// This will be used to add 8 days to the previous date
DateTime endDate = startDate.AddDays(8);
}
<h3>Dates Characteristics</h3>
<pre>Starting Date: @startDate
Ending Date: @endDate
======================================</pre>
This would produce:
Starting Date: 10/6/1988 12:00:00 AM Ending Date: 10/14/1988 12:00:00 AM ======================================
If you pass a positive value to the DateTime.AddDays() method, a number of days is added to the DateTime variable.
Adding a Time Span Value
To allow you to add a date-based value to a date, the DateTime structure is equipped with a method named Add. Its syntax is:
public DateTime Add (TimeSpan value);
This method takes a TimeSpan argument and it returns a DateTime object. To use it, create a TimeSpan object that contains the value(s) to add. Here is an example:
@page @model Exercise.Pages.ExerciseModel @{ DateTime startDate = new DateTime(1988, 10, 6); // 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); } <h3>Dates Characteristics</h3> <pre>Starting Date: @startDate Ending Date: @endDate ======================================</pre>
This would produce:
Starting Date: 10/6/1988 12:00:00 AM Ending Date: 3/27/1989 12:00:00 AM ======================================
Subtracting Days from a Date Value
To let you subtract date values, the DateTime structure is equipped with an overloaded method named Subtract. The syntax of one of them takes a DateTime object:
public TimeSpan Subtract(DateTime value);
When calling this version, create and pass a DateTime object. This version produces a TimeSpan object. From that returned object, you can identify the value that was produced.
As an alternative to the DateTime.Subtract() method, you can call the DateTime.Add() method. If you want to subtract some days from a date, pass a negative value to the DateTime.AddDays() method. 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 is:
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.
Subtracting a Time Span Value
The other version of the DateTime.Subtract() method takes a TimeSpan object as argument:
public DateTime Subtract(TimeSpan value);
This time, pass a TimeSpan object to the method. As an alternative, the DateTime structure makes it possible to subtract a value from a date. To do this, pass a negative value to the DateTime.Add() method. This would produce a new DateTime object. Here is an example:
@page
@model Exercise.Pages.ExerciseModel
@{
DateTime startDate = new DateTime(1988, 10, 6);
// This will be used to add 172 days to the previous date
TimeSpan ts = new TimeSpan(-10, 0, 0, 0);
// Pass the TimeSpan object to the date
DateTime endDate = startDate.Add(ts);
// And display it
}
<h3>Dates Characteristics</h3>
<pre>Starting Date: @startDate
Ending Date: @endDate
======================================</pre>
This would produce:
Starting Date: 10/6/1988 12:00:00 AM Ending Date: 9/26/1988 12:00:00 AM ======================================
Month-Based Operations
Adding Months to a Date Value
To let you 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 a number of months. If you pass the argument with a positive value, the months are added to the date.
Subtracting Months to a Date
To subtract a number of months from a date, you can call the DateTime.AddMonths() method. If you pass the argument with a negative value, the number of months is subtracted from the date.
Year-Based Operations
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 has the logical operators configured appropriately.
To compare two dates, apply the desired Boolean operator the same way you would proceed for two variables of primitive types. Here is an example:
@page
@model Exercise.Pages.ExerciseModel
@{
DateTime startDate = new DateTime(1988, 10, 6);
// This will be used to add 8 days to the previous date
DateTime endDate = startDate.AddDays(8);
}
<h3>Dates Characteristics</h3>
<p>Starting Date: @startDate</p>
<p>Ending Date: @endDate</p>
<p>-----------------------------------------------------------</p>
@if(startDate < endDate)
<p>@startDate occurs before @endDate</p>
<p>===========================================================</p>
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 ===========================================================
Practical Learning: Ending the Lesson
|
|||
Previous | Copyright © 2001-2022, FunctionX | Friday 15 October 2021 | Next |
|