C#检查字符串是否含日期格式及代码返回false问题求助
Hey there! Let's troubleshoot why your DateTime.TryParse is always returning false and get that date range check working correctly.
Why DateTime.TryParse Fails
The issue here is straightforward: DateTime.TryParse is designed to parse a single date value, but your string is a range with two dates separated by "to" (like "15/02/2018 to 23/04/2018"). It can't handle this format out of the box, hence the consistent false result.
Solution 1: Split & Validate Each Date (Most Reliable)
This approach splits the string into individual dates, then validates each one explicitly. We'll use TryParseExact instead of TryParse to avoid culture-related parsing issues (since your date format is dd/MM/yyyy).
Here's the code:
string str = Request[columns[2][search]]; bool isDateRange = false; // First check if the string contains the "to" separator for date ranges if (str.Contains("to")) { // Split the string into start and end date parts string[] dateSegments = str.Split(new[] {"to"}, StringSplitOptions.RemoveEmptyEntries); // Make sure we have exactly two parts if (dateSegments.Length == 2) { DateTime startDate, endDate; // Use TryParseExact to validate each date with the exact format bool isStartDateValid = DateTime.TryParseExact( dateSegments[0].Trim(), "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out startDate ); bool isEndDateValid = DateTime.TryParseExact( dateSegments[1].Trim(), "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out endDate ); // Both dates need to be valid for this to be a valid range isDateRange = isStartDateValid && isEndDateValid; } } // Now isDateRange will be true only if str is a valid dd/MM/yyyy to dd/MM/yyyy range
Solution 2: Regular Expression (For Quick Format Checks)
If you just need to verify the string matches the date range format (and don't need to work with the actual DateTime objects immediately), a regex can work. Note that regex can't fully validate if the dates are logically valid (e.g., it'll match "31/04/2018" even though April only has 30 days), so combine it with date parsing if you need strict validity.
Here's the regex approach:
using System.Text.RegularExpressions; string str = Request[columns[2][search]]; // Regex pattern to match "dd/MM/yyyy to dd/MM/yyyy", allowing optional whitespace Regex dateRangePattern = new Regex(@"^\s*\d{2}/\d{2}/\d{4}\s+to\s+\d{2}/\d{2}/\d{4}\s*$"); bool matchesDateRangeFormat = dateRangePattern.IsMatch(str); // Optional: If you need to ensure the dates are real, add the split/validation step here if (matchesDateRangeFormat) { // Use the split method from Solution 1 to confirm the dates are valid }
Key Notes
- Always use
TryParseExactwith a specific format andCultureInfo.InvariantCulturewhen dealing with fixed date formats—this avoids bugs from varying system culture settings (e.g., a US system would interpret15/02/2018as invalid viaTryParsesince it expectsMM/dd/yyyy). - Regex is great for quick format checks, but never rely on it alone for validating date logic—always pair it with date parsing if you need to ensure the dates actually exist.
内容的提问来源于stack exchange,提问作者ExpertGenie

