SoFunction
Updated on 2025-03-06

C# method to verify whether a given string form date is legal

This article example describes how C# can verify whether a given string form date is legal. Share it for your reference. The specific analysis is as follows:

This C# code is used to verify the validity of dates and also makes simple processing for irregular dates entered by the user. For example, if the user enters "Today", the code will think that the user wants to return today's date. In addition, the purely numeric date can be parsed, such as: 20130906

/// <summary>
/// Verify whether the date is legal and simple handling of irregularities/// </summary>
/// <param name="date">Date</param>public static bool IsDate(ref string date)
{
  //If it is empty, the verification is considered qualified  if (IsNullOrEmpty(date))
  {
 return true;
  }
  //Clear the spaces in the string to be validated  date = ();
  //replace\  date = (@"\", "-");
  //replace/  date = (@"/", "-");
  //If you find the Chinese character "Today", it is considered to be the current date  if (("now") != -1)
  {
 date = ();
  }
  try
  {
 // Use conversion to test whether it is a ruled date character date = (date).ToString("d");
 return true;
  }
  catch
  {
 //Return false if there is a non-number in the date string if (!IsInt(date))
 {
   return false;
 }
 #region parses pure numbers //Analysis of 8-digit pure numbers if ( == 8)
 {
   //Get the year, month, day   string year = (0, 4);
   string month = (4, 2);
   string day = (6, 2);
   // Verify legality   if (Convert.ToInt32(year) &lt; 1900 || Convert.ToInt32(year) &gt; 2100)
   {
 return false;
   }
   if (Convert.ToInt32(month) &gt; 12 || Convert.ToInt32(day) &gt; 31)
   {
 return false;
   }
   //Splicing date   date = (year + "-" + month + "-" + day).ToString("d");
   return true;
 }
 //Analysis of 6-digit pure numbers if ( == 6)
 {
   //Get year and month   string year = (0, 4);
   string month = (4, 2);
   // Verify legality   if (Convert.ToInt32(year) &lt; 1900 || Convert.ToInt32(year) &gt; 2100)
   {
 return false;
   }
   if (Convert.ToInt32(month) &gt; 12)
   {
 return false;
   }
   //Splicing date   date = (year + "-" + month).ToString("d");
   return true;
 }
 //Analysis of 5-digit pure numbers if ( == 5)
 {
   //Get year and month   string year = (0, 4);
   string month = (4, 1);
   // Verify legality   if (Convert.ToInt32(year) &lt; 1900 || Convert.ToInt32(year) &gt; 2100)
   {
 return false;
   }
   //Splicing date   date = year + "-" + month;
   return true;
 }
 //Analysis of 4-digit pure numbers if ( == 4)
 {
   //Get year   string year = (0, 4);
   // Verify legality   if (Convert.ToInt32(year) &lt; 1900 || Convert.ToInt32(year) &gt; 2100)
   {
 return false;
   }
   //Splicing date   date = (year).ToString("d");
   return true;
 }
 #endregion
 return false;
  }
}

I hope this article will be helpful to everyone's C# programming.