Check multiple date formats using DateTime.TryParse ()

I use the text field validation method.

public bool ValidateDateTimeTextBoxes(params TextBox[] textBoxes) { DateTime value = DateTime.Today; //string dateFormat = "dd/mm/yyyy"; foreach (var textBox in textBoxes) { if (!DateTime.TryParse(textBox.Text, out value)) { return false; } } return true; } 

I also want to check the format. This requires mm/dd/yyyy , but want it to be dd/mm/yyyy

+8
c #
source share
5 answers

Try DateTime.TryParseExact

 DateTime dt; DateTime.TryParseExact(textBox.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt); 

If you want to check multiple formats as you update in your question, you can use another TryParseExact overload TryParseExact , which takes the format parameter as an array of strings.

 string[] formats = { "dd/MM/yyyy", "MM/dd/yyyy" }; DateTime.TryParseExact(txtBox.Text, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out value)); 

Pay attention to the format string. As you already noted the dd/mm/yyyy format. Here mm represents minute not month. Use mm to represent the month.

+17
source share
 DateTime.TryParseExact(textBox.Text, "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out outDt)) 
+2
source share
  public bool ValidateDateTimeTextBoxes(params TextBox[] textBoxes) { DateTime value = DateTime.Now; //string dateFormat = "dd/mm/yyyy"; foreach (var textBox in textBoxes) { if (!DateTime.TryParse(textBox.Text,"dd/mm/yyyy",new CultureInfo("en-US"), DateTimeStyles.None out value)) { return false; } } return true; } 
+1
source share

Try using TryParseExact

Converts the specified string representation of the date and time to the equivalent of a DateTime. The format of the string representation must exactly match the specified format. The method returns a value indicating whether the conversion was successful.

 DateTime.TryParseExact(DateValue, "dd/mm/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out outDatetime); 
+1
source share

Use TryParseExact as well as faster. Example:

 using System; using System.Globalization; class Program { static void Main() { string dateString = "27/05/2012"; // <-- Valid string dtformat = "dd/mm/yyyy"; DateTime dateTime; if (DateTime.TryParseExact(dateString, dtformat, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime)) { Console.WriteLine(dateTime); } } } 
+1
source share

All Articles