I have so far made this code:
Console.WriteLine("Hey, what your name?");
Console.Write("Enter your name: ");
string YourName;
YourName = Console.ReadLine();
Console.WriteLine("Wow what a nice name!");
Console.ReadLine();
Console.WriteLine("What about your age?");
Console.Write("Enter your year of birth: ");
string BirthYear;
BirthYear = Console.ReadLine();
Console.Write("Enter your month of birth (number not actual month): ");
string BirthMonth;
BirthMonth = Console.ReadLine();
Console.Write("Enter you day of birth: ");
string BirthDate;
BirthDate = Console.ReadLine();
DateTime myBirthAge = DateTime.Parse(BirthMonth BirthDate BirthYear);
TimeSpan myAge = DateTime.Now.Subtract(myBirthAge);
Console.WriteLine(myAge.TotalDays);
Console.ReadLine();
I am a beginner at coding and I do not know how to make it so that when I do ask for the persons day of birth, year of birth, and month of birth, it can calculate the number of days they are alive. I tried putting the strings into the DateTime.Parse(); and other methods, but it did not work. How am I able to fix this?
CodePudding user response:
You can either create a date string and call Parse
, or convert the inputs to integers and use the DateTime
constructor. I'd prefer the latter since it removes any ambiguity that is inherent in date parsing:
DateTime myBirthAge = new DateTime(int.Parse(BirthYear),
int.Parse(BirthMonth),
int.Parse(BirthDay));
CodePudding user response:
I want to preface this by saying that, given the way you're rading the date values, I would personally choose this solution by D Stanley over this answer. I'm simply providing this so that you can understand why your code was failing.
The issue with your code (DateTime.Parse(BirthMonth BirthDate BirthYear);
)
is that the provided date will effectively become the following string value:
03011923
Or worse:
311923
Your system will (presumably) be expecting the date in the format MM/dd/yyyy
, so it won't understand those values. This also wouldn't work on my system as my locale is English (UK) (and thus the default thread culture is English UK) so mine would expect dd/MM/yyyy
.
We can improve the differing culture issue by passing a specific culture to DateTime.Parse
. For example we can use the invariant culture, which expects dates in MM/dd/yyyy
format:
DateTime.Parse(BirthMonth BirthDate BirthYear, System.Globalization.CultureInfo.InvariantCulture);
But then we still have the issue of how the date is formatted. You'll want to combine the constituent parts with dividers:
BirthMonth "/" BirthDate "/" BirthYear
Or better yet:
$"{BirthMonth}/{BirthDate}/{BirthYear}"
Putting it all together we get:
DateTime myBirthAge = DateTime.Parse($"{BirthMonth}/{BirthDate}/{BirthYear}", System.Globalization.CultureInfo.InvariantCulture);