title: How to validate date format in C#
body: <p>I want to check if a given string is a valid .net date format. </p>
  
  <p>so i have the following function that checks if the date format is correct</p>
  
  <pre><code>    public void IsValidDateFormat(string dateFormat)
      {
          var flag = true;
          try
          {
              DateTime.ParseExact(DateTime.Now.ToString(),
                  dateFormat,
                  System.Globalization.CultureInfo.InvariantCulture);
          }
          catch (Exception ex)
          {
              flag = false;
          }
  
         return flag;
      }
  </code></pre>
  
  <p>However, The method is not working as expected. For a valid date format also it returns false.</p>
  
  <p><code>dateFormat = ,,</code>  => returns false =>Passed<br>
  <code>dateFormat = someinvalidformat</code>  => returns false =>Passed<br>
  <code>dateFormat = MM/dd/yyyy</code>  => returns false => Not Passed   </p>
  
  <p>So <code>MM/dd/yyyy</code> is valid dateformat. But method returns false.</p>
  
  <p>Is there a better way to check if given date format is valid .Net date format?</p>
  
  <p><strong>Update 1</strong><br>
  I understand why method fails for <code>MM/dd/yyyy</code> or for other valid date formats. I am not asking why it fails. <code>MM/dd/yyyy</code> is just common valid date time format i am using here for example.<br>
  I am looking for a way to check if the given date format is valid .Net date format. So it could be any .Net date format.</p>