You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 TryParseExact with a specific format and CultureInfo.InvariantCulture when dealing with fixed date formats—this avoids bugs from varying system culture settings (e.g., a US system would interpret 15/02/2018 as invalid via TryParse since it expects MM/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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:38:12