0

I am getting an error 'String was not recognized as a valid DateTime.' by using the following code.

NewRow["ExpiryDate"] = DateTime.ParseExact(SelectedRow.Cells[9].Text, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture); 

where selectedRow is row of database. The code is written in RowCommand event. Value in SelectedRow.Cells[9].Text is in dd-MM-yyyy format on client side where as it is different on server side.

How can I write generic code that will work for all datetime format?

Microsoft Developer
  • 5,229
  • 22
  • 93
  • 142

3 Answers3

5

You have to specify the date format for dd-MM-yyyy data.

Use following method:

DateTime.ParseExact Method (String, String[], IFormatProvider, DateTimeStyles)

Sample:

 string[] formats = { "dd-MMM-yyyy", "dd/MMM/yyyy", "dd-MM-yy","d/M/yy"};
 string dateString = "1/1/10";

 DateTime date=DateTime.ParseExact(dateString ,formats,
    System.Globalization.CultureInfo.InvariantCulture,
     System.Globalization.DateTimeStyles.None);
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
0

You are receving the dd-MM-yyyy format, but in parseExact you have given dd/MM/yyyy. Replace '/' with '-'

Sudhakar B
  • 1,465
  • 9
  • 16
0

AVD

Try this.... or similiar

NewRow["ExpiryDate"] = DateTime.ParseExact(SelectedRow.Cells[9].Text, "dd/MM/yyyy".Replace("/", "-"), System.Globalization.CultureInfo.InvariantCulture);
Zoya
  • 405
  • 3
  • 10
  • 21