简体   繁体   中英

DateTime parsing error while parsing dd/MM/yyyy format. String was not recognized as valid datetime

I create a string using values from certain page elements in my web user control as below

string bookingdate = ddlDate.SelectedItem.Text 
                       + "/" + ddlMonth.SelectedValue + "/" 
                       + ddlMonth.SelectedItem.Text.Substring(4, 2);

and getting "String was not recognized as a valid DateTime." error on the following line

cmd.Parameters.Add(new SqlParameter("@ArrivalDate", SqlDbType.DateTime)).Value = 
    DateTime.ParseExact(bookingdate, "dd/MM/yyyy", CultureInfo.InvariantCulture);

How can I alter the value of this string "bookingdate" to troubleshoot the problem.

As I can understand you need Indian Date Format that is dd/mm/yyyy . So in your code, pass parameter as string and in sql handle it using Convert(date,Convert(datetime,@ArrivalDate,103)) . Use date as your datatype if you need only date and is on Sql 2008 or above otherwise

Convert(datetime,@ArrivalDate,103) and leave your datatype as datetime

In cs:

cmd.Parameters.AddWithValue("@ArrivalDate", bookingdate);

So ddlMonth contains items in this format (you posted the link to your page):

<option value="08">Aug 14</option>

Now you're trying to extract the month and year part from it:

ddlMonth.SelectedValue + "/" + ddlMonth.SelectedItem.Text.Substring(4, 2)

Your format string is this: dd/MM/yyyy

Do you already see the problem? The format string expects four digits for the year.

Instead use this format string: dd/MM/yy

DateTime.ParseExact(bookingdate, "dd/MM/yy", CultureInfo.InvariantCulture);

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