Click here to Skip to main content
15,944,733 members
Please Sign up or sign in to vote.
3.75/5 (4 votes)
See more:

I have a problem while converting date which is entered by user in format of 'MM-dd-yyyy'.
I used
dt = convert.todatetime(txt_date.text);

but it shows error as String was not recognized as a valid DateTime.

Eg. I want to convert date "06-16-2011" as datetime using convert.todatetime.
Updated 15-May-11 23:48pm
Dalek Dave 16-May-11 4:16am    
Edited for Grammar and Readability.


  CultureInfo format_dt = new CultureInfo(en-US);
  dt = DateTime.ParseExact(txt_date.Text, "MM-dd-yyyy", format_dt)
 catch (FormatException)

This is working
Share this answer
ambarishtv 16-May-11 4:46am    
my 5 for "FormatException" handling :)
If you want to convert a string to a date time, and it is going to always be in a specific format, rather than the culture of the PC it is running on, then use the DateTime.ParseExact[^] Method:
dt = Date.ParseExact("05-16-2011","dd-MM-yyyy", CultureInfo.InvariantCulture)
Share this answer
Dalek Dave 16-May-11 4:17am    
This is true.
ambarishtv 16-May-11 4:43am    
the given syntax is not valid one.
how to manage when txt_date.text is invalid date format.

dt = convert.todatetime(txt_date.text.ToString("MM-dd-yyyy"));
Share this answer
DateTime date= DateTime.ParseExact(dtText.Text, "MM-dd-yyyy", null);

Use it .

It may help you
Share this answer
DateTime.TryParseExact() is the best way to convert string with custom format to DateTime datatype

string myDate = "06-16-2011";
            DateTime dt;
            //verify given date is valid or not
            if (DateTime.TryParseExact(myDate, "dd-mm-yyyy", CultureInfo.InvariantCulture,     System.Globalization.DateTimeStyles.None, out dt))

             //invalid date format

Share this answer
try this

//check for one more Thing TextBox1.Text should not be empty before converting
string dt = TextBox1.Text;
DateTime k = Convert.ToDateTime(dt);
Share this answer

string dtText = TextBox1.Text;
Label1.Text = Convert.ToDateTime(dtText).ToString();
Share this answer
You can use DateTime.Parse or DateTime.ParseExact instead of Convert.ToDate

Try out below link,

Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900