There are 2 fundamental portions to the task at hand:
1. Understand what the user has input as a DateTime object
2. Display that same DateTime object is a specific format.
For the first part, the best thing is to utilize the
DateTime.TryParse
method.
string dag, month, year;
private void buttonOK_Click(object sender, EventArgs e)
{
string date = maskedTextBoxDato.Text;
DateTime dto;
if (!DateTime.TryParse(date, out dto))
{
} else {
And the second part of your task is going to be displaying this.
Normally the recommended way would be simply use the
ToString
method and utilize either the Standard- or Custom Date and Time format strings.
However... you apparently need to use a
switch...case
block for formatting the date.
As we did get a valid DateTime object in the first part of this, that means we have the various properties; such as Year, Month, and Date- all as properties of type Int. This will make things easier as you don't need to worry about leading zeroes not being there; for instance on 10-2-2020 vs 10-02-2020.
string MonthName;
switch(dto.Month) {
case 1:
MonthName = "Januar";
break;
}
labelFacit.Text = MonthName;
The rest of your date components will be easy conversions as well, simply using the
ToString method on those properties as well.
string day = dto.Day.ToString();
string month = dto.Month.ToString();
string year = dto.Year.ToString();
And if you need the leading zeroes, there are Standard Numeric Format strings available
References:
DateTime.TryParse Method (System) | Microsoft Docs[
^]
DateTime.Month Property (System) | Microsoft Docs[
^]
Standard date and time format strings | Microsoft Docs[
^]
Custom date and time format strings | Microsoft Docs[
^]
Standard numeric format strings | Microsoft Docs[
^]