DateTime.ParseExact give the error: String was not recognized as a valid DateTime

StackOverflow https://stackoverflow.com/questions/12507438

  •  03-07-2021
  •  | 
  •  

Вопрос

I want to parse DateTime, here my code:

var datastring =p1.ItemArray[2].ToString();
var format = "dd.MM.yyyy";
var date = DateTime.ParseExact(datastring,format,CultureInfo.InvariantCulture);

p1 - is DataRow, in p1.ItemArray[2] I have value of DateTime

In watch p1.ItemArray[2] have this value : "09/03/2012 00:00:00" his type is DateTime

After parsing throws error: String was not recognized as a valid DateTime.

Это было полезно?

Решение

You could include the time in your format as it seems the string you are trying to parse contains the time:

var format = "dd/MM/yyyy hh:mm:ss";

Also I would recommend you using the TryParseExact method as it provides a better defensive programming pattern instead of throwing exceptions.

Другие советы

IMHO you should use

var datastring = p1.ItemArray[2].ToString();
var format = "dd/MM/yyyy HH:mm:ss";
var date = DateTime.ParseExact(datastring, format, CultureInfo.InvariantCulture);

With ParseExact you must provide exact format of date contained in string

Change this:

var format = "dd.MM.yyyy";

With this:

var format = "dd/MM/yyyy HH:mm:ss";

because parseExact will expect to receive the same format that you specified which is "dd.MM.yyyy". You can try:

var format = "dd.MM.yyyy";
var datastring =p1.ItemArray[2].ToString(format);

Most probably due to the difference between your Server locale and the UI locale

One easier method will be to specify the globalization details in the web.config

like

<configuration>
   <system.web>
      <globalization culture="en-GB"/>
   </system.web>
</configuration>

OR in more detail

<globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="en-GB" uiCulture="en-GB" />

But be sure this wont clash with your application in general

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top