Convert a dd/MM/yyy string to Datetime

Asked

Viewed 7,804 times

2

I have a date filter that should receive the information from a textbox and convert it to Datetime, so I can then compare it to another date. The textbox sends the date in the dd/MM/yyyy format, but at the time of converting values where the date passes 12, an error occurs that the string cannot be recognized as a Datetime.

I’ve looked at several sites and similar responses in this and other, but nothing works.

If there is no simple way, I will have to appeal to format the string before going to date and go to the same gambit.

Code

List<PainelFormularioMetodologia> PesquisaDataMaxima(List<PainelFormularioMetodologia> listaPesquisa)
    {
        List<PainelFormularioMetodologia> listaRetorno = new List<PainelFormularioMetodologia>();

        //O erro acontece aqui

        DateTime dataFim = DateTime.ParseExact(txtDataFim.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
        DateTime dataIni = DateTime.ParseExact(txtDataInicio.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);

       /////////////////////

        if (dataFim < dataIni)
            Util.Alert("Data final é menor que Data inicial.");

        foreach (PainelFormularioMetodologia item in listaPesquisa)
        {                
            if (item.Dt_ModificaProcesso_data <= dataFim)
                listaRetorno.Add(item);
        }

        if (listaRetorno.Count == 0)
            Util.Alert("Verifique o filtro: Modificado em");

        return listaRetorno;            
    }

Error

[Formatexception: The Datetime represented by the string is not supported in Calendar System.Globalization.Gregoriancalendar.]

inserir a descrição da imagem aqui

Worked as:

DateTime dataFim = DateTime.ParseExact(txtDataFim.Text, "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("pt-BR"));
DateTime dataIni = DateTime.ParseExact(txtDataInicio.Text, "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("pt-BR"));
  • 1

    Post what as the date is inserted and which error has generated please.

  • I posted now, when the field is like in the Beginning, the search is done normally, but when I pass the 12 the bug catches.

  • Try instead of Cultureinfo.Invariantculture tries to use new Cultureinfo("en-US")

  • As you can see on this link https://msdn.microsoft.com/pt-br/library/w2sa9yss(v=vs.110). aspx, the command Converte a representação de cadeia de caracteres especificada de uma data e hora para sua DateTime equivalente usando o formato especificado e as informações de formato específicas da cultura. Then your date must be coming with an hour or something else, hence the mistake. The second parameter of the function has to be the format that its date is now and not the format that it will be.

  • So the second parameter should be MM/dd/yyyy? I also checked what is coming from txtDataFim and Start and is not coming time, only the date as dd/MM/yyyy

  • 1

    Tries to replace the CultureInfo.InvariantCulture for CultureInfo.CreateSpecificCulture("pt-BR")

  • @Joaorezende how is coming the value of txtDataInicio and txtDataFim

  • @Joaorezende made a quick example https://dotnetfiddle.net/J0cVBo

  • They are coming like that: Start date: 04/12/2014 and End date: 04/30/2016

  • I’m testing your answer, cool example, so you should be right what I did.

  • It was also not recognized if I for day greater than 12, must be wanting q the string come as MM/dd/yyyy. I will try to replace it with creatspecificitculture

  • It worked! Thank you very much Thiago, Marlon and Richard! createSpecificCulture worked, I’ll edit and post the right way if someone has the same question.

  • @Joaorezende Poste an answer to how he got it. He can help someone else too.

  • TL;DR; This question is not duplicated of this other?

Show 9 more comments

2 answers

6

Tries to replace the CultureInfo.InvariantCulture for CultureInfo.CreateSpecificCulture("pt-BR") - Richard Dias

It worked and stayed that way:

DateTime dataFim = DateTime.ParseExact(txtDataFim.Text, "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("pt-BR"));
DateTime dataIni = DateTime.ParseExact(txtDataInicio.Text, "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("pt-BR"));

Thank you to everyone who helped.

-3

Try to do this:

DateTime data = DateTime.MinValue;

try {
 data = DateTime.Parse(dataString);
} catch{ data = DateTime.MinValue}

if(data.CompareTo(DateTime.MinValue) != 0)
  //data correta
else
  //data incorreta
  • Using a Try catch to solve this type of problem generates unnecessary processing.

Browser other questions tagged

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