简体   繁体   中英

String was not recognized as a valid DateTime

I know such questions are in ton in SO but my situation seems little weird to me.

I have a textbox with a calendar extender control on my aspx page

Default format is "d" in extenders date format property. When I choose my date say 15th May 2012 from the calendar,it gives me 5/15/2012 , which is fine.

Since its a string and my db field is oftype datetime, so I am using

Convert.ToDateTime(TextBox.Text);   // TextBox.Text = 5/15/2012

But it throws the exception, string was not recognized as valid datetime .

I then Change the code and used DateTime.Parse() but the issue remains. Then i tried to reformat the date something like this,

Convert.ToDateTime(string.Format("0:MM-dd-yyyy",TextBox.Text)).Date

but still its throwing exceptions..

Please help me.

Use the following,

DateTime dt = DateTime.ParseExact(TextBox.Text, "dd/MM/yyyy", 
                                  CultureInfo.InvariantCulture);

There's probably a difference between your system's DateTime format and the DateTiem format the extender uses.

I suppose that your dev machine date-time format is not equal to MM/DD/YYYY, but something else (for example DD/MM/YYYY). Have a look on your computer Regional settings to see your system date time format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM