string was not recognized as a Valid datetime

Asked

Viewed 3,671 times

0

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

1 answer

4


This is because your application does not define any culture. Therefore, the culture used will be the one 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 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 they will always be the same, you can use a ParseExact to convert the string for DateTime.

It is interesting you pay attention to these details of culture, maybe it is much better to take care of it than to use the 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"));
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.