Check several date formats using DateTime.TryParse()

后端 未结 5 2025
北荒
北荒 2021-01-05 02:34

I\'m using a method to validate textboxes.

    public bool ValidateDateTimeTextBoxes(params TextBox[] textBoxes)
    {
        DateTime value = DateTime.Toda         


        
5条回答
  •  旧巷少年郎
    2021-01-05 03:06

    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 updated in your question then you can do using another overload method of TryParseExact which takes format parameter as array of string.

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

    Please take care of format string. As you have mentioned format as dd/mm/yyyy. Here mm represents the minute not the month. Use MM for the month representation.

提交回复
热议问题