Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check several date formats using DateTime.TryParse()

Tags:

c#

I'm using a method to validate textboxes.

    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 want to check the format too. It requires mm/dd/yyyy, but want it to be dd/mm/yyyy

like image 278
Etrit Avatar asked May 27 '13 07:05

Etrit


People also ask

How does DateTime TryParse work?

TryParse(String, DateTime)Converts the specified string representation of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded.

How do you check if the date is in dd mm yyyy format in C #?

Use DateTime. TryParseExact to try to parse it: string text = "02/25/2008"; DateTime parsed; bool valid = DateTime. TryParseExact(text, "MM/dd/yyyy", CultureInfo.

What is the format of DateTime?

For example, the "d" standard format string indicates that a date and time value is to be displayed using a short date pattern. For the invariant culture, this pattern is "MM/dd/yyyy". For the fr-FR culture, it is "dd/MM/yyyy". For the ja-JP culture, it is "yyyy/MM/dd".


2 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 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.

like image 171
Sachin Avatar answered Oct 11 '22 04:10

Sachin


DateTime.TryParseExact(textBox.Text, "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out outDt))
like image 26
Rohit Agrawal Avatar answered Oct 11 '22 04:10

Rohit Agrawal