SoFunction
Updated on 2025-04-06

Implementation code in C# to determine and verify whether the string is in date format

This article introduces how to determine whether it is a date given a string. This article will introduce two methods: one is to judge whether the string is time, and if so, it will be converted into a time variable. The second method is to make only judgments.

In C#, there is a specialized function for judging the format, that is, TryParse. TryParse exists in different type classes (such as int, string, DateTime). In TryParse, there are generally two parameters, one is the string to be judged, and the other is the variable that saves the result after conversion.

Copy the codeThe code is as follows:

string strDate = "2014-4-3";
DateTime dtDate;

if ((strDate, out dtDate))
{
    (dtDate);
}
else
{
throw new Exception("not the correct date format type!");
}

In addition to the above aspects, we can also use the Parse function to handle it, please see the following function:

Copy the codeThe code is as follows:

public bool IsDate(string strDate)
{
    try
    {
        (strDate);
        return true;
    }
    catch
    {
        return false;
    }
}

The first is to judge the time format and convert it into one time, and the second is to make only judgments, each with its own purpose.