How to avoid automatic datetime field formation in Mysql with Asp Net?

Asked

Viewed 20 times

0

I’m trying to read datetime fields with Mysql.Data.Mysqlclient, but the value that returns is always different from what is in the database, for example in this bank "2002-05-01 00:00:00.000" but the code returns "5/1/02 12:00:00 AM" . Code similar to the one I’m using below, the difference of the official is the number of fields I pick, I appreciate any help.

using (MySqlConnection connection = new MySqlConnection(con))
using (MySqlCommand cmd = connection.CreateCommand())
{
    cmd.CommandText = "select * from tablename";
    connection.Open();
    var r = cmd.ExecuteReader();
    while (r.Read())
    {
        Console.WriteLine(r["dt_compra"].ToString());   // resultado 5/1/02 12:00:00 AM // aqui deveria ser 2002-05-01 00:00:00.000
    }
}

1 answer

0

Well you can set Culture info en-US in your application but this can lead to many changes like currency formatting etc, so I think the best way would be to convert the date even if you don’t want to change the settings of the application

Best way

DateTime.Parse(r["dt_compra"].ToString(), CultureInfo.GetCultureInfo("pt-BR"))

Safest way

DateTime result;
DateTime.TryParse(r["dt_compra"].ToString(), CultureInfo.GetCultureInfo("pt-BR"), DateTimeStyles.None, out result)
  • I tested but it happens the same thing, it’s like if mysql already converts then in r["dt_purchase"] already comes the date with an attempt to talk ai gets the string broken

Browser other questions tagged

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