经验计算问题求助:dd.mm.yy格式入职日期解析异常
Alright, let's figure out why your date parsing is misbehaving and fix this properly. Here's the breakdown and solution:
Core Issue: Unspecified Date Format
The biggest problem here is that DateTime.Parse relies on your system's default culture settings to interpret the input date. If your system uses a date format like MM/dd/yyyy (common in the US), it will misinterpret your dd.mm.yyyy input—for example, 20.04.2015 gets read as month 20 (which is invalid, so it falls back to defaulting the month to 01, hence the 01/20/2015 result you saw).
You need to explicitly tell the parser exactly what format to expect, instead of leaving it to guess.
Fix Syntax & Logic Errors First
Your original code has a few obvious bugs that need addressing:
Console.ReadLine(console.ReadLine()_dataformat,null)is invalid syntax—you just needConsole.ReadLine()to get user input.DateTime.todayis case-sensitive in C#; it should beDateTime.Today.- The typo
exsisttodaysdatedoesn't make sense—replace it with a clear error message like "The date cannot be later than today." - Your loop structure is incomplete (the
breakimplies you're in a loop, but it's not shown in your code snippet).
Corrected Code Using DateTime.TryParseExact
This code explicitly enforces the dd.mm.yyyy format, handles invalid inputs gracefully, and calculates work experience once a valid date is entered:
DateTime dateOfJoining; bool isInputValid = false; while (!isInputValid) { Console.WriteLine("Please enter your joining date (format: dd.mm.yyyy):"); string userInput = Console.ReadLine(); // Explicitly define the expected date format and use invariant culture to avoid system locale issues if (DateTime.TryParseExact( userInput, "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dateOfJoining)) { if (dateOfJoining <= DateTime.Today) { isInputValid = true; Console.WriteLine($"Valid joining date: {dateOfJoining:dd.MM.yyyy}"); // Calculate work experience TimeSpan totalExperience = DateTime.Today - dateOfJoining; int years = totalExperience.Days / 365; int remainingDays = totalExperience.Days % 365; int months = remainingDays / 30; int days = remainingDays % 30; Console.WriteLine($"Work experience: {years} years, {months} months, {days} days"); } else { Console.WriteLine("Error: The date cannot be later than today. Please try again."); } } else { Console.WriteLine("Error: Please enter a valid date in the dd.mm.yyyy format (e.g., 20.04.2015)."); } }
Key Improvements:
DateTime.TryParseExact: Eliminates guesswork by specifying exactly what date format to accept.dd= two-digit day,MM= two-digit month,yyyy= four-digit year.CultureInfo.InvariantCulture: Ensures the dot (.) is recognized as the date separator, regardless of what your system's default locale uses.- Loop Until Valid Input: The code will keep prompting the user until they enter a properly formatted date that's not in the future.
- Clear Error Messages: Guides the user on what they did wrong, instead of generic prompts.
内容的提问来源于stack exchange,提问作者sam

