Reputation: 1609
I am slowly learning to do some simple console applications with C# and have now faced an issue what I do not manage to solve. I've tried searching for a solution all over the Stack Overflow / Internet, but either I don't know how to properly search for it, or there is no answer to what I'm seeking.
Situation: I am creating a simple console app that asks the following things from user: First name, Family name, Age.
Every prompt (question) has been introduced to the user via the following code:
System.Console.Write("What is your date of birth? ");
String dob = System.Console.ReadLine();
I have made a simple checker for the names, which seeks if they're between 1-30 characters and if they are, the application writes the results in a text document.
Question: How can I check if the date of birth has been written in the following format: DD.MM.YYYY?
Upvotes: 1
Views: 148
Reputation: 30032
TryParseExact
is your way :
DateTime dt = new DateTime();
bool success = DateTime.TryParseExact(dob, "dd.MM.yyyy", CultureInfo.CurrentCulture,
DateTimeStyles.AssumeLocal, out dt);
If dob is in correct format, isInCorrectFormat
will be true
and dt
will hold the correct parsed DateTime
object.
Upvotes: 1
Reputation: 45947
This will return if it's a valid date or not:
String dob = System.Console.ReadLine();
DateTime dtResult;
bool IsValid = DateTime.TryParseExact(dob, "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dtResult);
But in case of e.g. January 1st you can't detect a month/day swap. That will only result to false if the day > 12
Upvotes: 2