C method to verify that a given date in string form is valid
- 2021-01-22 05:18:32
- OfStack
This article demonstrates C#'s method of verifying that a given date in string form is valid. Share with you for your reference. The specific analysis is as follows:
The C# code is used to verify the validity of the date. It also handles the irregular date entered by the user. For example, if the user enters "today", the code will assume that the user is returning today's date
/// <summary>
/// Verify that the date is valid , The irregularity is simply treated
/// </summary>
/// <param name="date"> The date of </param>
public static bool IsDate(ref string date)
{
// If it is empty, the validation is considered qualified
if (IsNullOrEmpty(date))
{
return true;
}
// Clear the whitespace in the string to validate
date = date.Trim();
// replace \
date = date.Replace(@"\", "-");
// replace /
date = date.Replace(@"/", "-");
// If you find a Chinese character " today ", Is the current date
if (date.IndexOf(" today ") != -1)
{
date = DateTime.Now.ToString();
}
try
{
// Test for a regular date character with a conversion
date = Convert.ToDateTime(date).ToString("d");
return true;
}
catch
{
// Returns if a non-number exists in the date string false
if (!IsInt(date))
{
return false;
}
#region Parse the pure numbers
// right 8 Bits of pure numbers are parsed
if (date.Length == 8)
{
// Get year, month and day
string year = date.Substring(0, 4);
string month = date.Substring(4, 2);
string day = date.Substring(6, 2);
// Validation of validity
if (Convert.ToInt32(year) < 1900 || Convert.ToInt32(year) > 2100)
{
return false;
}
if (Convert.ToInt32(month) > 12 || Convert.ToInt32(day) > 31)
{
return false;
}
// Date of joining together
date = Convert.ToDateTime(year + "-" + month + "-" + day).ToString("d");
return true;
}
// right 6 Bits of pure numbers are parsed
if (date.Length == 6)
{
// For years
string year = date.Substring(0, 4);
string month = date.Substring(4, 2);
// Validation of validity
if (Convert.ToInt32(year) < 1900 || Convert.ToInt32(year) > 2100)
{
return false;
}
if (Convert.ToInt32(month) > 12)
{
return false;
}
// Date of joining together
date = Convert.ToDateTime(year + "-" + month).ToString("d");
return true;
}
// right 5 Bits of pure numbers are parsed
if (date.Length == 5)
{
// For years
string year = date.Substring(0, 4);
string month = date.Substring(4, 1);
// Validation of validity
if (Convert.ToInt32(year) < 1900 || Convert.ToInt32(year) > 2100)
{
return false;
}
// Date of joining together
date = year + "-" + month;
return true;
}
// right 4 Bits of pure numbers are parsed
if (date.Length == 4)
{
// For years
string year = date.Substring(0, 4);
// Validation of validity
if (Convert.ToInt32(year) < 1900 || Convert.ToInt32(year) > 2100)
{
return false;
}
// Date of joining together
date = Convert.ToDateTime(year).ToString("d");
return true;
}
#endregion
return false;
}
}
I hope this article is helpful to your C# program design.