Home  >  Q&A  >  body text

C#: timestamp truncated?

Running the command text in MySQL Workbench will return 2023-04-09 11:37:05.508

The following code is truncated to: 2023-04-09 11:37:05. I want to know why?

The column is defined as datetime(3).

Use the following sample code to reproduce:

var connection = new MySqlConnection(connectionString.ToString());

connection.Open();

const string commandText = @"SELECT logged_at FROM logs WHERE application_id = @id ORDER BY id DESC LIMIT 1";

var cmd = new MySqlCommand(commandText, connection);
cmd.Parameters.Add("@id", MySqlDbType.Int32).Value = 3;

var reader = cmd.ExecuteReader();

if (reader.Read())
{
    Console.WriteLine(reader["logged_at"].ToString());
}

connection.Close();

P粉738821035P粉738821035236 days ago308

reply all(1)I'll reply

  • P粉420958692

    P粉4209586922024-02-26 19:43:16

    By default, DateTime.ToString() does only extract DateTime to seconds. This means that the underlying value you have is more accurate, but not printed. You can check this simply by placing a breakpoint and observing the variable values ​​of the debugged application.

    To get more verbose output, you can use a custom formatter For example:

    DateTime dt = (DateTime)reader["logged_at"];
    Console.WriteLine(dt.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture));

    reply
    0
  • Cancelreply