Error in DateTime.TryParse

-2

I'm having a problem converting using the code below:

        string vcto = "29/01/2018";
        DateTime data;

        Boolean resp = DateTime.TryParse(vcto, out data);

        if (resp == false)
        {
            MessageBox.Show("ERRO NA CONVERSAO");
        }  

It is returning false . but the date is correct.

I do not have access to the machine running the code, I just checked via log . On my development machine it works perfectly.

What can make TryParse() fail? The date is correct.

    
asked by anonymous 28.09.2018 / 21:37

2 answers

2

You have to add the specific culture to the application to know what kind of data it is waiting for, in case I imagine it is waiting for the Brazilian, then this would be:

using System;
using System.Globalization;

public class Program {
    public static void Main() {
        if (!DateTime.TryParse("29/01/2018", new CultureInfo("pt-BR"), DateTimeStyles.None, out var data)) Console.WriteLine("ERRO NA CONVERSAO");
    }
}

See running on .NET Fiddle . And in Coding Ground . Also put it in GitHub for future reference .

Documentation for TryParse() .

It works on your machine because it is already configured like this, not all are.

    
28.09.2018 / 23:04
1

You can use the following code:

string vcto = "29/01/2018";
DateTime data;

Boolean resp = DateTime.TryParseExact(vcto, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out data);

if (resp == false)
{
    MessageBox.Show("ERRO NA CONVERSAO");
}
    
28.09.2018 / 22:11