string was not recognized as a valid datetime

0

Hello. This problem is only occurring when I place the site on iis. I have tried several solutions, but I can not solve it. Below 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 the visual studio of the application server where the iis stays, no errors occur, only when I execute on iis.

    
asked by anonymous 24.05.2017 / 20:49

1 answer

2

This is because your application does not define any culture. Therefore, the culture used will be the one that is defined 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 otherwise, so the date format will not be valid .

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

It's interesting to look at these details of culture, maybe it's much better to take care of it than using ParseExact , but without more details there's no way to 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"));
}
    
24.05.2017 / 20:58