I am writing a program in C #, which involves a simple questioning of users with the subsequent output of data.

How to organize in the C # console application the receipt of data on the date of his birth from the user?

    3 answers 3

    Make a method that polls the input in a loop until the correct value is entered:

    DateTime inputDoB() { DateTime dob; // date of birth string input; do { Console.WriteLine("Введите дату рождения в формате дд.ММ.гггг (день.месяц.год):"); input = Console.ReadLine(); } while (!DateTime.TryParseExact(input, "dd.MM.yyyy", null, DateTimeStyles.None, out dob)); return dob; } 

    Using:

     var dob = inputDoB(); 

    You can set an arbitrary format for the input date. For example, "dMyyyy" , which allows you to enter a date in the form 1.4.2017 .

    • Does not accept as input "1.04.2017" . - VladD
    • @VladD, well, it says "Enter your date of birth in the format dd.MM.gggg", your input does not match the mask ... Although, of course, this can be painful for the user - Andrey NOP
    • @AlexanderPetrov - thank you very much! - Narykin Ivan

    It all depends on your requirements, if simple manual input is enough, you can use one of the answers sent earlier.

    If you are implementing a console GUI, you can think of something like this:

     class ConsoleDatePicker { public int Left { get; set; } public int Top { get; set; } public DateTime SelectedDate { get; set; } public ConsoleDatePicker(int left, int top) { Left = left; Top = top; SelectedDate = DateTime.Today; } public ConsoleDatePicker() : this(0, 0) { } string[] months = { "янв", "фев", "мар", "апр", "май", "июн", "июл", "авг", "сен", "окт", "ноя", "дек" }; public void Show() { int oldLeft = Console.CursorLeft, oldTop = Console.CursorTop; ShowFrame(); ShowMonth(); ShowCursor(); Console.SetCursorPosition(oldLeft, oldTop); } void ShowFrame() { Console.SetCursorPosition(Left, Top); Console.Write("╔══════════════════════╗"); Console.SetCursorPosition(Left, Top + 1); Console.Write("║ ║"); Console.SetCursorPosition(Left, Top + 2); Console.Write("╟──────────────────────╢"); for (int topAdd = 3; topAdd <= 15; ++topAdd) { Console.SetCursorPosition(Left, Top + topAdd); Console.Write("║ ║"); } Console.SetCursorPosition(Left, Top + 16); Console.Write("╚══════════════════════╝"); } void ShowMonth() { Console.SetCursorPosition(Left, Top + 1); Console.Write($"║ {months[SelectedDate.Month - 1]} {SelectedDate.Year:0000} ║"); string[,] days = new string[6, 7]; int week = 0; int dayOfWeek = (int)FirstDayOfMonth(SelectedDate).DayOfWeek - 1; if (dayOfWeek == -1) dayOfWeek = 6; int daysInMonth = LastDayOfMonth(SelectedDate).Day; for (int day = 1; day <= daysInMonth; ++day) { days[week, dayOfWeek] = $"{day,2}"; ++dayOfWeek; if (dayOfWeek == 7) { ++week; dayOfWeek = 0; } } for (int row = 0; row < 6; ++row) for (int column = 0; column < 7; ++column) { Console.SetCursorPosition(Left + 2 + column * 3, Top + 4 + row * 2); Console.Write(days[row, column] ?? " "); } } void ShowCursor() { int column = (int)SelectedDate.DayOfWeek - 1; if (column == -1) column = 6; int row = (SelectedDate.Day + (int)FirstDayOfMonth(SelectedDate).DayOfWeek - 2) / 7; Console.SetCursorPosition(Left + 1 + column * 3, Top + 3 + row * 2); Console.Write("┌──┐"); Console.SetCursorPosition(Left + 1 + column * 3, Top + 4 + row * 2); Console.Write("│"); Console.SetCursorPosition(Left + 4 + column * 3, Top + 4 + row * 2); Console.Write("│"); Console.SetCursorPosition(Left + 1 + column * 3, Top + 5 + row * 2); Console.Write("└──┘"); } void EraseCursor() { int column = (int)SelectedDate.DayOfWeek - 1; if (column == -1) column = 6; int row = (SelectedDate.Day + (int)FirstDayOfMonth(SelectedDate).DayOfWeek - 2) / 7; Console.SetCursorPosition(Left + 1 + column * 3, Top + 3 + row * 2); Console.Write(" "); Console.SetCursorPosition(Left + 1 + column * 3, Top + 4 + row * 2); Console.Write(" "); Console.SetCursorPosition(Left + 4 + column * 3, Top + 4 + row * 2); Console.Write(" "); Console.SetCursorPosition(Left + 1 + column * 3, Top + 5 + row * 2); Console.Write(" "); } DateTime FirstDayOfMonth(DateTime date) { return new DateTime(date.Year, date.Month, 1); } DateTime LastDayOfMonth(DateTime date) { return FirstDayOfMonth(date.AddMonths(1)).AddDays(-1); } public DateTime GetDate() { int oldLeft = Console.CursorLeft, oldTop = Console.CursorTop; bool cursorVisible = Console.CursorVisible; Console.CursorVisible = false; ConsoleKeyInfo key; do { Console.SetCursorPosition(oldLeft, oldTop); key = Console.ReadKey(); DateTime newDate = SelectedDate; if (key.Key == ConsoleKey.RightArrow) newDate = SelectedDate.AddDays(1); if (key.Key == ConsoleKey.LeftArrow) newDate = SelectedDate.AddDays(-1); if (key.Key == ConsoleKey.DownArrow) newDate = SelectedDate.AddDays(7); if (key.Key == ConsoleKey.UpArrow) newDate = SelectedDate.AddDays(-7); if (newDate != SelectedDate) { EraseCursor(); bool changeMonth = newDate.Month != SelectedDate.Month; SelectedDate = newDate; if (changeMonth) ShowMonth(); ShowCursor(); } } while (key.Key != ConsoleKey.Enter); Console.CursorVisible = cursorVisible; Console.SetCursorPosition(oldLeft, oldTop); return SelectedDate; } } 

    You can use it like this:

      ConsoleDatePicker cdp = new ConsoleDatePicker(5, 5); cdp.Show(); DateTime date = cdp.GetDate(); Console.WriteLine("Вы выбрали {0:d}", date); 

    enter image description here


    Another option for use in the console GUI is simpler, less cumbersome, and most likely more convenient. Without the use of pseudographics, so it does not depend on the code page used (although in different cultures the representation of the date must be different dd.MM.yyyy / yyyy-MM-dd - if you wish, implement it yourself).

     class ConsoleDatePickerMini { public int Left { get; } public int Top { get; } public DateTime SelectedDate { get; private set; } public ConsoleDatePickerMini(int left, int top, DateTime date) { Left = left; Top = top; SelectedDate = date; } public ConsoleDatePickerMini(int left, int top) : this(left, top, DateTime.Today) { } public ConsoleDatePickerMini() : this(0, 0) { } public void Show() { int oldLeft = Console.CursorLeft, oldTop = Console.CursorTop; ShowDate(); Console.SetCursorPosition(oldLeft, oldTop); } public DateTime GetDate() { int oldLeft = Console.CursorLeft, oldTop = Console.CursorTop; bool cursorVisible = Console.CursorVisible; Console.CursorVisible = false; int f = 0; ConsoleKeyInfo key; do { ShowCursor(f); Console.SetCursorPosition(oldLeft, oldTop); key = Console.ReadKey(); if (key.Key == ConsoleKey.RightArrow) f = (f + 1) % 3; if (key.Key == ConsoleKey.LeftArrow) f = (f + 2) % 3; if (key.Key == ConsoleKey.UpArrow || key.Key == ConsoleKey.DownArrow) { int additive = key.Key == ConsoleKey.UpArrow ? 1 : -1; if (f == 0) SelectedDate = SelectedDate.AddDays(additive); else if (f == 1) SelectedDate = SelectedDate.AddMonths(additive); else if (f == 2) SelectedDate = SelectedDate.AddYears(additive); } ShowDate(); } while (key.Key != ConsoleKey.Enter); Console.CursorVisible = cursorVisible; Console.SetCursorPosition(oldLeft, oldTop); return SelectedDate; } void ShowDate() { Console.SetCursorPosition(Left, Top); Console.Write(" "); Console.SetCursorPosition(Left, Top + 1); Console.Write(SelectedDate.ToString("dd.MM.yyyy")); Console.SetCursorPosition(Left, Top + 2); Console.Write(" "); } void ShowCursor(int field) { int offset = new[] { 1, 4, 9 }[field]; // или по хакерски: int offset = (field + 1) * (field + 1); Console.SetCursorPosition(Left + offset, Top); Console.Write("+"); Console.SetCursorPosition(Left + offset, Top + 2); Console.Write("-"); } } 

    Use similar to the previous one. Looks like that:

    enter image description here

    • Cool! True, in the Japanese locale (-_-, sometimes you have to work in it) the "layout" is broken. Only an enlightened sensei can understand the logic of output in this locale. - Alexander Petrov
    • @ Andrei - very cool! But for my understanding it is still too difficult. Thank you very much! - Narykin Ivan

    Try this:

     Console.WriteLine("Введите дату рождения в формате (DD.MM.YYYY): \n"); string input = Console.ReadLine(); string[] split = input.Split('.'); double day = Double.Parse(split[0]); double month = Double.Parse(split[1]); double year = Double.Parse(split[2]); 
    • one
      1,5.7,8.2016,3 with Russian locale - then what? - Qwertiy
    • these are user down problems. The code has nothing to do with it. - Exodium
    • 2
      And I would say that a programmer who, with some kind of fright, keeps the day for a month and a year as a double . - Qwertiy
    • @Exodium: A good programmer should not drop the program with any user input. You will fall, for example, when you enter привет . Darn! - VladD
    • @Exodium - Thank you very much! - Narykin Ivan