Dates Fundamentals

Introduction

A date is a measure of non-spatial units that have elapsed in a set period. The most basic unit of a date is called a "day". A group of 28, 29, 30, 0r 31 consecutive days (depending on some factors) is called a month. A groupd of 12 consecutive months is called a year.

Practical LearningPractical Learning: Introducing Tool Bars

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

Creating a Date Value

To let you create and manage dates, the .NET Framework provides a structure named DateOnly. Therefore, to create a date value, you can first declare a variable of type DateOnly. To assist you with initializing the variable, the DateOnly structure is equipped with three constructors. There is a default constructor. Its syntax is:

public DateOnly();

Presenting a Date Value

We have seen that one way to get a date value is to declare a DateOnly variable. In later sections, we will see other ways to get a date value. However you get that value, at some point, you may want to display it. The easiest way to display a date value is to use its variable.

Converting a Date Value to a String

Before displaying a date value, you can first convert that value to a string. To support this, the DateOnly structure overrides the ToString() method that is overloaded with four versions. One of the versions takes no argument. 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. Here is an example:

private void btnCreate_Click(object sender, EventArgs e)
{
    DateOnly doDateDefault = new DateOnly();

    txtDateDefault.Text = doDateDefault.ToString();
}

This would display:

Converting a Date Value to a String

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.

Filling a Date

A date is a technique of identifying a period using three numbers: the year, the month, and the day. Each is an integer value. To create a date that holds such values, the DateOnly structure is equipped with a constructor that takes three integer arguments. Its syntax is:

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

As you can see, this constructor takes three arguments: a value for the year, a value for the month, and a value for the day, respectively. Here is an example of creating a date object:

private void Exercises_Load(object sender, EventArgs e)
{
    DateOnly independance = new DateOnly(1960, 1, 1);
}

Getting a Date Value

If you want your users to provide a date value, you have various options. In a graphical application, the primary way to deal with a date value is to use a Windows control.

Date-Based Controls

A Tex Box

The most common way to allow a user to provide values in an application is with a text box. You can use it to request date value. In this case, you should make sure the label associated with the text box clearly indicates to the user what you want. Here is an example:

Month-Calendar

A Masked Tex Box

Probably the biggest problem with the text box is that it allows any value, which allows to provide a value that doesn't fit the one expected. To assist you, the .NET Framework provides a custom text box in a class named MaskedTextBox. This class is derived from the same TextBoxBase class as TextBox:

[System.ComponentModel.DefaultBindingProperty("Text")]
public class MaskedTextBox : System.Windows.Forms.TextBoxBase

This class is represented in the Toolbox by a control of the same name. Therefore, to have a masked text box in your application, click the MaskedTextBox control in the Toolbox and click the form or another container.

To make the MaskedTextBox support various types of values, the class is equipped with a property named Mask, which is of type string:

public string Mask { get; set; }

This property allows you to provide a string that contains the type of format you want the text box to hold. Therefore, after adding a masked text box to a form, to make the control support date values, configure its Mask field in the Properties window. It provides a dialog box you can use:

Masked Text Box - Input Mask

You can use that dialog box to specify how the masked text box will control the value it receives.

The Month-Calendar Control

A calendar is a technique to organize the days of a year. Normally, the days are grouped by months and a calendar can contain 12 consecutive months of one year.

To let you provide a calendar in an application, the .NET Framework provides a class named MonthCalendar. This class is derived from the Control class:

[System.ComponentModel.DefaultBindingProperty("SelectionRange")]
public class MonthCalendar : System.Windows.Forms.Control

To help you work visually, the MonthCalendar class is represented in the Toolbox by a control of the same name. Therefore, to get a calendar in our application, in the Toolbox, click the MonthCalendar button and click a container, such as a form. This would display a calendar with one month:

Month-Calendar

By default, the month-calendar control displays with one month. If you want it to display more than one month, after adding the control on a form, to display the months horizontally, enlarge the control:

Month-Calendar

If you want it to display one month below another, increate the height of the control:

Month-Calendar

The Date Picker

Probably the biggest advantage of the month-calendar control is that it displays a full month. Probably the biggest disadvantage of the month-calendar control is that it uses too much space on a form. To let you use the amount of space of a text box, the .NET Framework provides a class named DateTimePicker, which also is derived from the Control class:

[System.ComponentModel.DefaultBindingProperty("Value")]
public class DateTimePicker : System.Windows.Forms.Control

A control of this class is available in the Toolbox. Therefore, to get a calendar from this class, in the Toolbox, click the DateTimePicker button and click somewhere on a form.

Requesting a Date Value

Parsing a Date Value

When you request a value from a user, if you are not using special control such as a month-calendar or a date picker, the value may be provided to you as a string. If you are planning to use that value as a date, you may have to convert it first. To assist you with this operation, the DateOnly structure is equipped with the traditional Parse() method used with other types. Here are examples of calling it:

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

        private void btnCreate_Click(object sender, EventArgs e)
        {
            DateOnly doDateHired = new DateOnly();
            DateOnly doOrientatiopnDate = new DateOnly();

            doDateHired = DateOnly.Parse(txtDateHired.Text);
            doOrientatiopnDate = DateOnly.Parse(txtOrientationDate.Text);
        }
    }
}

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 DateOnly variable, a colon, and a format.

A Date as a Type

Introduction

As we will see in various examples, the DateOnly 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 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:

public class Employee
{
    private DateOnly dtHired;

    public State()
    {
        dt = new DateOnly();
    }
}

A Date Property

A property of DateOnly type is created like that of a structure. Whenever you need to initialize it or give it a value, proceed as for any structure.

To create a complete date property, you can first declare a private DateOnly field in a class, record, or structure. Then, in the body of the class, record, or structure, create the property with a get and a set/init clauses. Here is an example:

internal record Purchase
{
    DateOnly dDay;

    public DateOnly InventoryDate
    {
        get { return dDay; }
        init { dDay = value; }
    }
}

In the same way, you can create a read-only or an automatic property. Here is an example:

public class EmploymentApplication
{
    public DateOnly DateHired { get; set; }

    public EmploymentApplication()
    {
        DateHired = new DateOnly(2020, 8, 16);
    }
}

Either way, after creating the property, you can access it. You can declare a variable of the class and access the property. Here is an example:

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

        private void btnCreate_Click(object sender, EventArgs e)
        {
            EmploymentApplication ea = new EmploymentApplication();

            ea.DateHired = DateOnly.Parse(txtDateHired.Text);
            ea.OrientationDate = DateOnly.Parse(txtOrientationDate.Text);

            lblDateHired.Text = ea.DateHired.ToString();
            lblOrientationDate.Text = ea.OrientationDate.ToString();
        }
    }

    internal record EmploymentApplication
    {
        DateOnly dDay;

        public DateOnly DateHired
        {
            get { return dDay; }
            set { dDay = value; }
        }

        public DateOnly OrientationDate { get; set; }
    }
}

An Array of Date Values

To create an array of date values, declare the DateOnly variable as an array. To initialize the array, you can provide a value for each item using a constructor of the DateOnly structure. Here is an example:

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

        private void btnCreate_Click(object sender, EventArgs e)
        {
            DateOnly[] dateOfAdmissionToFederation = new DateOnly[]
            {
                new DateOnly(1823, 12, 20),
                new DateOnly(1824,  2,  7),
                new DateOnly(1823, 12, 22),
                new DateOnly(1824,  5,  7)
            };
        }
    }
}

After creating the array, you can access its elements. You can access one element at a time or you can loop through the array.

Introduction to the Characteristics of a Date Value

Introduction

The pieces of information of the DateOnly structure are:

The Default Date Value

The default constructor of the DateOnly structure initializes the date to January 1st, 0001 at midnight. Here is an example that shows it:

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

            DateOnly tm = new();

            lblDefaultDate.Text = $"Default date and time: {tm}";
        }
    }
}

This would produce:

The Default Date Value

The Minimum Date Value

The minimum date value is the lowest value that a DateOnly object can hold. This value is January 1st, 0001. This value is represented by the MinValue constant member of the DateOnly structure.

The Maximum Date Value

The highest date and time that a DateOnly object can hold in the structure is called MaxValue and it is set at December 31, 9999.

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:

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

            DateOnly date = new DateOnly(2022, 4, 22);
            string strMonth = date.ToString("MM");

            lblOriginalDate.Text = date.ToString();
            lblMonth.Text = strMonth;
        }
    }
}

This would produce:

Rules of Date Formats - MM

If the number is higher than 9, it would display as 10, 11, or 12.

MMM

The triple M as MMM (in uppercase) gets the short name of the month using three letters. This variable is defined by the operating system. The short 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:

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

            DateOnly date = new DateOnly(2022, 4, 22);
            string strMonth = date.ToString("MMM");

            lblOriginalDate.Text = "Original Date: " + date.ToString();
            lblMonth.Text = "Month:            " + strMonth;
        }
    }
}

This would display:

Rules of Date Formats - MMM

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:

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

            DateOnly date = new DateOnly(2022, 4, 22);
            string strMonth = date.ToString("MMMM");

            lblOriginalDate.Text = "Original Date:    " + date.ToString();
            lblMonth.Text        = "Month:              " + strMonth;
        }
    }
}

This would produce:

Rules of Date Formats - MMMM

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:

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

            DateOnly date = new DateOnly(2022, 4, 22);
            string strDay = date.ToString("dd");

            lblOriginalDate.Text = "Original Date:    " + date.ToString();
            lblDay.Text          = "Day:                  " + strDay;
        }
    }
}

This would display:

Rules of Date Formats - dd

yy

The double y is used to get the numeric year with the last two digits. Here is an example:

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

            DateOnly date = new DateOnly(2024, 8, 22);
            string strYear2Digits = date.ToString("yy");

            lblOriginalDate.Text = "Original Date:    " + date.ToString();
            lblYear.Text         = "Year:                " + strYear2Digits;
        }
    }
}

This would display:

Rules of Date Formats - yy

yyyy

The yyyy string is used to get all four digits of a year. Here is an example:

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

            DateOnly date = new DateOnly(2024, 8, 22);
            string strYear4Digits = date.ToString("yyyy");

            lblOriginalDate.Text = "Original Date:    " + date.ToString();
            lblYear.Text         = "Year:                  " + strYear4Digits;
        }
    }
}

This would display:

Rules of Date Formats - yyyy

If the year was provided with two digits, such as 98, it would still be produced with 4 digits. Consider the following example:

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

            DateOnly date = new DateOnly(98, 8, 22);
            string strYear4Digits = date.ToString("yyyy");

            lblOriginalDate.Text = "Original Date:    " + date.ToString();
            lblYear.Text         = "Year:                  " + strYear4Digits;
        }
    }
}

This would display:

Rules of Date Formats - yyyy

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.

Dates Formats

Getting a Date Value From a Date-Only Object

You may have noticed that, by default, a DateOnly 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 DateOnly.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:

Customize Regional Options

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:

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

            DateOnly date = new DateOnly(98, 8, 22);
            string strYear = date.ToString("yyyy");

            lblOriginalDate.Text = "Original Date:               " + date.ToString();
            lblDate1.Text = "Date (M/d/yyyy):           " + date.ToString("M/d/yyyy");
            lblDate2.Text = "Date (M/d/yy):               " + date.ToString("M/d/yy");
            lblDate3.Text = "Date (MM/dd/yy):         " + date.ToString("MM/dd/yy");
            lblDate4.Text = "Date (MM/dd/yyyy):     " + date.ToString("MM/dd/yyyy");
            lblDate5.Text = "Date (yy/MM/dd):         " + date.ToString("yy/MM/dd");
            lblDate6.Text = "Date (yyyy-MM-dd):     " + date.ToString("yyyy-MM-dd");
            lblDate7.Text = "Date (dd-MMM-yy):      " + date.ToString("dd-MMM-yy");
        }

        private void btnCreate_Click(object sender, EventArgs e)
        {
            DateOnly doDateHired = new DateOnly();
            DateOnly doOrientationDate = new DateOnly();

            doDateHired = DateOnly.Parse(txtDateHired.Text);
            doOrientationDate = DateOnly.Parse(txtOrientationDate.Text);

            lblDateHired.Text       = doDateHired.ToString();
            lblOrientationDate.Text = doOrientationDate.ToString();
        }
    }
}

This would produce:

Dates Formats

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 DateOnly structure is equipped with a method named ToShortDateString. Its syntax is:

public string ToShortDateString();

Here is an example of calling this method:

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

            DateOnly date = new DateOnly(2024, 10, 8);
            string strDate = date.ToShortDateString();

            lblOriginalDate.Text = "Original Date:     " + date.ToString();
            lblShortDate.Text = "Short Date:          " + strDate;
        }
    }
}

This would produce:

Dates Formats

As another option to get a short date, on a DateOnly value, pass a "d" (one d in lowercase) string to the ToString() method. Here is an example:

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

            DateOnly date = new DateOnly(2024, 10, 8);
            string strDate = date.ToString("d");

            lblOriginalDate.Text = "Original Date:     " + date.ToString();
            lblShortDate.Text = "Short Date:         " + strDate;
        }
    }
}

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 DateOnly structure is equipped with a method named ToLongDateString, Its syntax is:

public string ToLongDateString ();

Here is an example of calling this method:

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

            DateOnly date = new DateOnly(2024, 10, 8);
            string strDate = date.ToLongDateString();

            lblOriginalDate.Text = "Original Date:   " + date.ToString();
            lblLongDate.Text = "Long Date:        " + strDate;
        }
    }
}

As another way to get a long date, pass a "D" (one d in uppercase) string to the ToString() method of a DateOnly value. Here is an example:

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

            DateOnly date = new DateOnly(2024, 10, 8);
            string strDate = date.ToString("D");

            lblOriginalDate.Text = "Original Date:   " + date.ToString();
            lblLongDate.Text = "Long Date:        " + strDate;
        }
    }
}

This would produce:

Dates Formats

Other Date Formats

The .NET Framework provides other formats, not regularly used but available. To get the name of a month and the day value of a DateOnly object, both separated by an empty space, pass a single M (lowercase or uppercase) as string to the ToString() method of a DateOnly object. Here is an example:

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

            DateOnly date = new DateOnly(2025, 10, 23);
            string strDate = date.ToString("M");

            lblOriginalDate.Text = "Original Date:       " + date.ToString();
            lblMonthAndDay.Text = "Month and Day:   " + strDate;
        }
    }
}

This would produce:

Dates Formats

To get (only) the month followed by the 4-digit year of a date value, pass a single Y (lowercase or uppercase) as string to the ToString() method of a DateOnly object. Here is an example:

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

            DateOnly date = new DateOnly(2025, 10, 23);
            string strDate = date.ToString("y");

            lblOriginalDate.Text = "Original Date:       " + date.ToString();
            lblMonthAndYear.Text = "Month and Year:   " + strDate;
        }
    }
}

This would produce:

Dates Formats

Practical LearningPractical Learning: Ending the Lesson


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