Reputation: 179
I need a way to whatsUrBirthDay = Console.ReadLine();
I could easily string whatsUrBirthDay;
but I want to be able to store their birthday so that I can 'relatively' easily recall it later and possibly do calculations with it.
Is there such a data type that will allow for a specific format of MM/DD/YYYY? I assume I can ask for Month as a string, then look for matching spelling or numbers to = some variable afterward, but surely there's an easier way?
Thanks in advance!
Edit I'd like to add that 'no', that is not the variable I'm choosing - just did it this way so you would understand what I'm asking for.
Upvotes: 2
Views: 3534
Reputation: 29036
Better you prompt the user to enter the date in some specific format, let it be dd-MM-yyyy
and show an example as well So that you can validate the input and store to a DateTime variable; See the code below:
string myDateFormat = "dd-MM-yyyy";
Console.WriteLine("Enter your Birth Date in the format {0} \n (example : {1}) : ",myDateFormat,DateTime.Today.ToString(myDateFormat));
DateTime userBirthday;
if (DateTime.TryParseExact(Console.ReadLine(), myDateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out userBirthday))
{
Console.WriteLine("You lived {0} days from {1} ", (DateTime.Today - userBirthday).TotalDays, userBirthday.ToString(myDateFormat));
}
else
{
Console.WriteLine("Wrongly formated input");
}
Note : if the input is not in desired format, then TryParseExact
will returns false based on that we can show warning message
Upvotes: 2
Reputation: 9659
As stated in the comments, the correct type for Dates is DateTime
. You can achieve what you want using the Parse
-method like that:
DateTime birthday = DateTime.Parse(Console.ReadLine(), out birthday);
DateTime also provides a TryParse
-Method which can be used to handle invalid input:
DateTime birthday;
// error handling similar to the following (if-clause work fine to)
while(!DateTime.TryParse(Console.ReadLine()))
{
Console.WriteLine("Invalid input, try again.");
}
If you are new to C# and want to know more about parsing dates/times, consider reading https://www.dotnetperls.com/datetime-parse which explains the most important aspects with simple examples (including error handling and such)
Upvotes: 0