tags:

views:

367

answers:

3

Hello all,

I have problem with the DateTime data type. Through a textbox I want to add person dateofbirth. As there is no date datatype in C# i am forced to use the DateTime datatype, but while converting TxtDateofBirth to DateTime i am getting an error, "String was not recognized as a valid DateTime." Here is my conversion the code. I kept this code in add event.

DateTime dateofbirth = Convert.ToDateTime(TxtDateOfBirth.Text);

What should I do?

Thanks,

Masum

+3  A: 

Use DateTime.ParseExact with a format string which only specifies the date part.

Alternatively, as this is user input, use DateTime.TryParseExact so you don't need to catch an exception if the user has entered a bad date:

using System;

class Test
{
    static void Main()
    {
        TestParsing("24/10/2009");
        TestParsing("flibble");
    }

    static void TestParsing(string text)
    {
        DateTime dt;

        if (DateTime.TryParseExact(text, "d", null, 0, out dt))
        {
            Console.WriteLine("Parsed to {0}", dt);
        }
        else
        {
            Console.WriteLine("Bad date");
        }
    }
}

Note that the format string "d" means "short date format" (see the "standard date and time form at strings" and "custom date and time format strings" pages in MSDN). "null" means "use the current culture" - so the above works for me in the UK, but you'd need to make the string "10/24/2009" in the US. You could specify a particular culture if you don't want to use the thread's current default. 0 means the default date and time style. Look at the MSDN page for more information.

Jon Skeet
+1  A: 

Alternatively , use a mask so that users can only enter valid dates. (See the c# section under examples on the link given)

Learning
+1  A: 

There is hardly anything one could add to Jon's answers, but in this case I'd like to make a point:

Try to understand that your problem is not because of the DateTime datatype but because your date string does not match the expected format (based on regional settings/thread culture) that the DateTime constructor.

You say that you are "forced" to use the DateTime datatype. You should keep in mind that Dates should always be treated as Dates. I've seen too many developers fall into the trap of using dates as strings (and performing split/search operations) rather than using DateTime because they feel that the latter is too complicated.

Cerebrus