C#: timestamp truncated?
P粉738821035
P粉738821035 2024-02-25 23:33:08
0
1
360

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粉738821035
P粉738821035

reply all(1)
P粉420958692

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));
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template