string was not recognized as a valid datetime

Wave. This problem is occurring only when I put the site in iis. I have tried several solutions, but I can not solve.Below is the code snippet where the problem occurs:

public DataTable SelecionaConsulta(string dtaIni,string dtaFim)
{
  return consulta.SELECT_VISITA(Convert.ToDateTime(dtaIni).ToString("yyyyMMdd"), Convert.ToDateTime(dtaFim).ToString("yyyyMMdd"));

}

Even when I run the system using visual studio from the application server where IIS is, no errors occur,only occurs when I run on iis.

 0
Author: LINQ, 2017-05-24

1 answers

This is because your application does not define any culture. Therefore, the culture used will be the one that is set in Windows.

Locally this will work because your Windows is configured with a culture (probably pt -*) and the date passed by parameter has the format used in this culture. On the server it will not work because the culture is different, so the date format will not be valid .

If you know the formats beforehand and are sure that they will always be you can use a ParseExact to convert string to DateTime.

It is interesting that you pay attention to these details of culture, perhaps it is much better to take care of this than to use ParseExact, but without more details it can not help you much.

public DataTable SelecionaConsulta(string dtaIni, string dtaFim)
{
     var formato = "dd/MM/yyyy HH:mm:ss";
     DateTime dataInicio;
     var dtIniConvertida = DateTime.TryParseExact(dtaIni, formato, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out dataInicio);

     DateTime dataFim;
     var dtFimConvertida = DateTime.TryParseExact(dtaFim, formato, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out dataFim);

     if(!dtIniConvertida && !dtFimConvertida)
         //Algo deu errado em uma das conversões

     return consulta.SELECT_VISITA(dataInicio.ToString("yyyyMMdd"), dataFim.ToString("yyyyMMdd"));
}
 3
Author: LINQ, 2017-05-24 18:58:33