Time Fundamentals

Introduction

A date is a spatial value that uses a set number of units. Probably the most fundamental unit of a date is a day. It starts at a point named midnight and ends just after the next midnight. A day is divided in 24 units named "hour" each. An hour is made of 60 units named "minute" each. The combination of an hour and a minute is referred to as time. Therefore, a time is a value to identify the number of units that have elapsed since midnight of a day. To support time values, the .NET Framework provides a read-only structure named TimeOnly.

Practical LearningPractical Learning: Introducing Tool Bars

  1. Start Microsoft Visual Studio
  2. Create a Windows Forms App application named Exercise10

Creating a Time Value

To let you create a time value, the TimeOnly structure is equipped with various constructors. Therefore, you can declare a variable of that type. As mentioned in the previous section, the primary components of a time value are the hour and the minute. Therefore, to let you create a normal time value, the TimeOnly structure is equipped with the following constructor:

public TimeOnly (int hour, int minute);

When calling this constructor, pass two required argument. The first, the hour, must be a small integer between 0 and 23. The second argument, the minute, must be a value between 0 and 59. Here is an example that creates TimeOnly object:

namespace DateValues
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();

            TimeOnly time = new TimeOnly(20, 38);
        }
    }
}

When creating a TimeOnly object, if you provide a negative value or a value higher than 23, the program will stop (it may not produce an exception and the compiler may not let you know that you provided a value out of range; if you want to be notified that a value out of range was provided, you can create your own conditional statement). In the same way, for the minute, if you provide a negative value or a value higher than 59, the program will fail, sometimes without a warning.

Converting a Time Value to a String

If you have a TimeOnly object, you can convert it to a String value. To make this operation possible, as seen for date values, after creating a time value, to let you display the value to the user, the TimeOnly structure is equipped with an overloaded 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:

public class Exercise
{
    public static int Main(string[] args)
    {
        TimeOnly time = new(16, 8, 44);
        string strTime = time.ToString();

        return 10;
    }
}

Introductory Characteristics of a Time Value

The Time Separator

As mentioned in our introduction, the two basic pieces of information you provide about a time value are the hour and the minute. Each part is represented with a number. In the time values, those two pieces of information must be distinguished as an hour followed, or separated, by a symbol. In US English, the symbol to separate the hour and the minute is the colon ":". An example is 8:25.

A Day in Two Parts

A day as a measure is in two parts divided by a point named noon. That noon period has a value of 12 or rather the eleventh hour and fifty-ninth minute. The first part of a day, from midnight to noon, is referred to as AM. The secong part of a day, from noon to the end of the day, is referred to as PM.

When creating a TimeOnly object, if you provide a value between 0 (included) and 12 (excluded), the time is considered to occur in the AM section. In this case, the compiler would produce a value that includes AM. Here is an example:

namespace DateValues
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();

            TimeOnly time = new TimeOnly(9, 38);

            lblOriginalTime.Text = "Original Time:  " + time.ToString();
        }
    }
}

This would produce:

Characteristics of a Time Value - AM-PM

The Hour of a Time Value

The primary piece of information about a time value is the hour. If you have a TimeOnly object, to let you get its hour value, the TimeOnly structure is equipped with a property named Hour. Its value is a number between 0 and 23. Here is an example:

namespace DateValues
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();

            TimeOnly time = new TimeOnly(9, 38);
            int hr = time.Hour;

            lblOriginalTime.Text = "Original Time:  " + time.ToString();
            lblResult.Text = "Hour Value:   " + hr.ToString();
        }
    }
}

This would produce:

The Hour of a Time Value

The Minute of a Time Value

The second piece of information about a time value is the minute. To let you get the minute value of a TimeOnly object, the structure is equipped with a property named Minute. Its value is a number between 0 and 59. Here is an example:

namespace DateValues
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();

            TimeOnly time = new TimeOnly(9, 38);
            int hr = time.Hour;
            int min = time.Minute;

            lblOriginalTime.Text = "Original Time:  " + time.ToString();
            lblHour.Text   = "Hour Value:      " + hr.ToString();
            lblMinute.Text = "Minute Value:    " + min.ToString();
        }
    }
}

This would produce:

The Minute of a Time Value

The Seconds of a Time Value

Introduction

In many cases, when you talk about time, you want precision. To make this possible, a minute is divided in sixty units named "second" each. Therefore, a more precise way to give time is to combine the hour, tne minute, and the second. To help you provide these three pieces of information, the TimeOnly structure is equipped with the following constructor:

public TimeOnly(int hour, int minute, int second);

Like it was mentionned for the minute, the value of the second must be between 0 (included and 59 (included). Here is an example:

namespace DateValues
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();

            TimeOnly time = new TimeOnly(9, 38, 26);

            lblOriginalTime.Text = "Original Time:  " + time.ToString();
        }
    }
}

This would produce:

Characteristics of a Time Value - AM-PM

The Milliseconds of a Time Value

To provide even more precision with time, a second can be divided in 1000 parts. Each part is called a milliseconds. To help you provide this value, the TimeOnly structure is equipped with the following constructor:

public TimeOnly(int hour, int minute, int second, int millisecond);

The millisecond argument must hold a number between 0 (included) and 999 (included). Here is an example:

namespace DateValues
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();

            TimeOnly time = new TimeOnly(9, 38, 26, 447);

            lblOriginalTime.Text = "Original Time:  " + time.ToString();
        }
    }
}

This would produce:

Characteristics of a Time Value - AM-PM

If you provide a negative value or a value higher than 999 for the millisecond argument, the program will fail. If you don't know the millisecond value, you can provide it as 0.

The Operating System and Application's Support for Time Value

Introduction

The rules used by the computer for time display can be seen in the Customize Regional Options dialog box:

Customize Regional Options

A Text Box for a Time Value

To let users provide time in your application, you can use a text box. Because a user can type just anything in a text box, in the accompanying label, you can add an indication for the type value you are expecting. Here is an example:

A Text Box for a Time Value

Converting a Value to Time

If you have a value, such as a string, that you must treat as time, you should first convert it to an appropriate time value. To assist you with this, the TimeOnly structure is equipped with the usual Parse() method. Here is an example of calling it:

Converting a Value to Time

private void btnValidate_Click(object sender, EventArgs e)
{
    TimeOnly arrivalTime = TimeOnly.Parse(txtArrivalTime.Text);
            
    txtAcceptedTime.Text = arrivalTime.ToString();
}

Converting a Value to Time

Converting a Value to Time

Windows Controls: A Masked Text Box

The masked text box allows you to configure one or more placeholders in the field of a text box so that the control can accept some characters, must reject some characters, and/or can display some other characters you will have put so the user cannot delete them.

To support masked text boxes, the .NET Framework provides a class named MaskedTextBox. To visually create a masked text box, from the Common Controls section of the Toolbox, click MaskedTextBox Masked Text Box and click the form. To programmatically create a masked text box, declare a variable of type MaskedTextBox and use the New operator to initialize it. Here is an example:

using System.Windows.Forms;

public class Exercise : Form
{
    MaskedTextBox txtFunctional;

    public Exercise()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        txtFunctional = new MaskedTextBox();
    }
}

To let you configure this text, the MaskedTextBox class is equipped with the Mask property named. You can use that property to specify how the control should behave and how it would assist the user.

Windows Controls: The Time Picker

The time picker is a control that allows the user to select a time value:

Date/Time Picker

One of the advantages of the time picker control is that it allows the user to select a time value instead of typing it. To support the time picker control, the .NET Framework provides the DateTimePicker class. To visually add a time picker to an application, in the Common Controls section of the Toolbox, click the DateTimePicker control DateTimePicker and click a form or other container. To transform a date time picker into a time picker control, change its Format property to a Time value. This can be done programmatically as follows:

using System.Drawing;
using System.Windows.Forms;

public class Exercise : System.Windows.Forms.Form
{
    public Exercise()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        DateTimePicker dtpTimeArrived = new DateTimePicker();
        dtpTimeArrived.Location = new Point(12, 12);
        dtpTimeArrived.Format = DateTimePickerFormat.Time;

    }
}

Formatting a Time Value

Introduction

As mentioned previously, the TimeOnly structure is equipped with the overloaded ToString() method. We saw the version that takes no argument and it produces a general time value. To let you control how to present a time value to the user, the TimeOnly structure is equipped with another version of the ToString() method. That version takes one argument. Its syntax is:

public string ToString(string? format);

When calling this method, the format is a string that contains the formula you want the compiler to follow, and there are rules you should/must follow for that argument.

Introduction to Time Rules and Formats

Like dates, time values follow some rules:

Time

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.

The Hours Format: hh

To get the hour value of a TimeOnly object, you can pass two "h" letters as the argument to the TimeOnly.ToString(string? format) method. Both letters can be provided in lowercase. Here is an example:

Converting a Value to Time

private void btnValidate_Click(object sender, EventArgs e)
{
    TimeOnly originalTime = TimeOnly.Parse(mtbOriginalTime.Text);
            
    txtHourValue.Text = originalTime.ToString("hh");
}

If the hour occurs before 10 in the morning, the value would display with a leading 0, such as 05. Here is an example of running the above program:

Hour Formats

Hour Formats

If the time is occurring after noon, if you pass the argument as a number => 12, the number 12 would be subtracter from the hour value, and the result would display with a leading 0. Here is another example of running the above program:

Hour Formats

Hour Formats

The Hours Format: HH

Another way to get the hour value of a TimeOnly object is to pass two "H" letters as the argument to the TimeOnly.ToString(string? format) method. Both letters must can be provided in uppercase. Here is an example:

private void btnValidate_Click(object sender, EventArgs e)
{
    TimeOnly originalTime = TimeOnly.Parse(mtbOriginalTime.Text);
            
    txtHourValue.Text = originalTime.ToString("HH");
}

If the hour occurs before 10 (in the morning), the value would display with a leading 0. Here is an example:

Hour Formats

Hour Formats

If the time value is after noon, the number would appear as you provided it. Here is an example:

Hour Formats

Hour Formats

The AM/PM Occurrence

Depending on how you indicate that the compiler should display a time value, in some cases, the hour may not indicate whether the time occurs before or after noon. To display this information, you can pass the argument to the TimeOnly.ToString(string? format) method as tt, ttt, or tttt (T in lowercases, no uppercase). Here is an example:

private void btnValidate_Click(object sender, EventArgs e)
{
    TimeOnly originalTime = TimeOnly.Parse(mtbProjectedTime.Text);

    txtMorningAfternoon1.Text = originalTime.ToString("tt");
    txtMorningAfternoon2.Text = originalTime.ToString("ttt");
    txtMorningAfternoon3.Text = originalTime.ToString("tttt");
}

Here is an example or running the above program:

Times Formats - The AM/PM Occurrence

Times Formats - The AM/PM Occurrence

The Minutes Format

If you want to get the minute value of a TimeOnly object, pass the argument to the TimeOnly.ToString(string? format) method as "mm" (two lowercase m letters). Here is an example:

namespace DateValues
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnValidate_Click(object sender, EventArgs e)
        {
            TimeOnly originalTime = TimeOnly.Parse(mtbOriginalTime.Text);
            
            txtMinuteValue.Text = originalTime.ToString("mm");
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}

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 of running the above program:

Hour Formats

Hour Formats

If the number is greater than 9, it would display the way it was provided.

The Seconds Formats

To get the number of seconds of a TimeOnly value, pass the argument to the TimeOnly.ToString(string? format) method as "ss" (two lowercase s letters). Here is an example:

Time

The Seconds Formats

private void btnValidate_Click(object sender, EventArgs e)
{
    TimeOnly originalTime = TimeOnly.Parse(mtbOriginalTime.Text);

    txtHoursValue.Text = originalTime.ToString("hh");
    txtMinutesValue.Text = originalTime.ToString("mm");
    txtSecondsValue.Text = originalTime.ToString("ss");
}

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 of running the above program:

Hour Formats

Hour Formats

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

Displaying a Complete Time Value

Combining Hours and Minutes

To display a time value, you can use the formats we reviewed in previous sections. For example, you may want to display the hour and the minute values. Of course you must distinguish the values by the official time separator as recognized by the operating system. Here is an example:

private void btnValidate_Click(object sender, EventArgs e)
{
    TimeOnly originalTime = TimeOnly.Parse(mtbProjectedTime.Text);

    txtArrivalTime.Text = originalTime.ToString("hh:mm");
}

Here is an example of running the above program:

Hour Formats

Hour Formats

Remember that you can use either hh or HH to control how the hour value should display.

Indicating Morning or Afternoon

Depending on how you specify the format of the TimeOnly.ToString(string? format) method, the user could face a value without knowing whether it occurs before or after noon. Therefore, whenever you can, you should indicate that information. To do this, instead of passing a combination of hours and minutes, pass the argument to the TimeOnly.ToString(string? format) method as "t" (one T in lowercase). Here is an example:

Time

The Seconds Formats

private void btnValidate_Click(object sender, EventArgs e)
{
    TimeOnly originalTime = TimeOnly.Parse(mtbOriginalTime.Text);

    txtHoursValue.Text = originalTime.ToString("hh");
    txtMinutesValue.Text = originalTime.ToString("mm");
    txtSecondsValue.Text = originalTime.ToString("t");
}

Here is an example of running the above program:

Hour Formats

Hour Formats

A Time Value with Seconds

We saw that, by default and in most cases (time sheets, flight arrival, etc), you need only the hour and the minutes values of time. Some operations need to display time that specifies the value of the seconds. In that case, add the seconds format to the combination of hours and minutes. O, you must apply the time separator. You can pass the format for the value with one s. If the number is less than 10, it would display without a leading 0. Here is an example:

private void btnValidate_Click(object sender, EventArgs e)
{
    TimeOnly originalTime = TimeOnly.Parse(mtbProjectedTime.Text);

    txtArrivalTime.Text = originalTime.ToString("hh:mm:s");
}

Here is an example of running the above program:

Hour Formats

Hour Formats

If the value of the seconds is less than 10 and you want it to display with a leading 0, pass the format as ss. Here is an example:

private void btnValidate_Click(object sender, EventArgs e)
{
    TimeOnly originalTime = TimeOnly.Parse(mtbProjectedTime.Text);

    txtArrivalTime.Text = originalTime.ToString("hh:mm:ss");
}

Here is an example of running the above program:

Hour Formats

Hour Formats

A Short Time Value

A time value is referred to as short if it includes only the hour and the minute. To help you display a short time, the TimeOnly structure is equipped with a method named ToShortTimeString. Its syntax is:

public string ToShortTimeString();

Based on this method, to display a time value on a short format, call this method on a TimeOnly object. Here is an example:

private void btnValidate_Click(object sender, EventArgs e)
{
    TimeOnly originalTime = TimeOnly.Parse(mtbTimeConsidered.Text);

    txtShortTimeFormat.Text = originalTime.ToShortTimeString();
}

Here is an example of running the above program:

Hour Formats - A Short Time Value

Hour Formats - A Short Time Value

Hour Formats - A Short Time Value

Hour Formats - A Short Time Value

A Long Time Value

A time value is considered long if it specifies the hour, the minute, the seconds, and the AM/PM section. To help you display a time value in a long format, the TimeOnly structure is equipped with a method named ToLongTimeString. Its syntax is:

public string ToLongTimeString();

Therefore, to display a time value on a long format, call this method on a TimeOnly object. Here is an example:

private void btnValidate_Click(object sender, EventArgs e)
{
    TimeOnly originalTime = TimeOnly.Parse(mtbTimeConsidered.Text);

    txtLongTimeFormat.Text = originalTime.ToLongTimeString();
}

Here is an example of running the above program:

Hour Formats - A Long Time Value

Hour Formats - A Long Time Value

Hour Formats - A Long Time Value

Hour Formats - A Long Time Value

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2024, FunctionX Friday 10 June 2022 Next