Error in Datetime.Tryparse

Asked

Viewed 1,455 times

-2

I have a problem with a conversion 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");
        }  

He is returning false. but the date is correct.

I don’t have access to the machine that’s running the code, I just checked via log. In my development machine works perfectly.

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

  • The input is different from the one reported in the question?

  • Can you see which language the machine is? It may be set up in a different language, probably English. You can test this by changing the month by the day in input.

  • Why not use : Convert.Todatetime() ?

  • Friend check is not the culture of your server, I’ve had problems with date conversion for this reason.

  • 1

    @Viniciusmatos because it would be a mistake to do this, it is partially correct.

2 answers

5


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

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");
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Documentation of TryParse().

It works on your machine because it’s already set up like this, not all are.

Fiat 147 todo detonado andando pelas ruas - Funcionar é diferente de estar certo

  • Thanks for the return, how do I check which culture windows is configured? It would be in the regional settings. The closest I got is the item that refers to date formatting. I would have something else to check?

  • No, it’s right there, but this has nothing to do with programming, it doesn’t matter to the programmer how is someone’s Windows.

  • Manieiro, forgive but I did not understand very well... but as I understood something on the machine is making the mistake to occur because this item of culture would not be it? I would like to check which culture this. Thanks for the help.

  • No, your program is wrong, it’s no problem in anyone’s machine, each leaves the machine as you want, it’s your program that has to take care of it right.

  • OK Thank you Maniero!

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");
}

Browser other questions tagged

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