Error TryParse of DateTime by converting string to Double format

0

I have a method that uses DateTime.TryParse to convert a string to type DateTime , but lately I realized that string with the format Double would also be being converted to date.

Is there any solution to fix this?

public class SaidaData : SaidaBase
{
    public SaidaData() { }
    public DateTime? Data { get; set; }
}

public class SaidaBase
{
    public SaidaBase() { }

    public Boolean Sucesso { get; set; }
    public String Mensagem { get; set; }
}

public class EntradaBase
{
    public EntradaBase() { }

    public String Conteudo { get; set; }

}

public class Entrada : EntradaBase
{
    public Entrada() { }

    public Int32 PosIni { get; set; }
    public Int32 Tamanho { get; set; }
    public String[] Array { get; set; }
}

#region ConverterCampoDateTime
public static SaidaData ConverterCampoDateTime(Entrada entrada)
{
    var saida = new SaidaData();

    DateTime valor;
    var convertido = DateTime.TryParse(entrada.Conteudo, out valor);

    if (convertido)
    {
        //saida.Mensagem = Resources.Mensagens.OK;
        saida.Mensagem = "OK";
        saida.Sucesso = true;
        saida.Data = valor;
    }
    else
    {
        //saida.Mensagem = Resources.Mensagens.Erro;
        saida.Data = null;
        saida.Mensagem = "ERRO";
        saida.Sucesso = false;
    }

    return saida;
}
#endregion

    
asked by anonymous 20.06.2016 / 14:50

1 answer

3

A parse method parses a text and tries to find something it recognizes there. If he recognizes and can generate a result, he will do so. He makes the best effort possible. If the intention is to only recognize a specific format you have to define this format, for this there is the TryParseExact() ". Example (the format, culture and style may have to be different):

DateTime.TryParseExact(entrada.Conteudo, "dd/MM/yyyy",
    CultureInfo.InvariantCulture, DateTimeStyles.None, out valor);

The confusion may occur because the data in this class is confusing. Maybe these classes are supporting too many things.

I find it strange to have this inheritance, but I do not know, I do not know the problem. I'm just giving a tip that the problem can be bigger and the architecture is problematic, the wrong conversion is just the symptom.

If it's to do such a class, I even have my doubts if you need properties .

These builders are unnecessary .

I do not much like the use of .Net types in place of C # types. It is taste, you can use it if you want, but it is an indication of invention:)

The good part is that you are using a Try method.

    
20.06.2016 / 15:07