How can I convert the Kafka message timestamp to date and time format in C#?

48 Views Asked by At

In my C# code I programmed a consumer with Confluent Kafka. I am reading the timestamp of the message and want to convert it to the know time and date format. I tried following code but get always Error: System.FormatException: String 'Confluent.Kafka.Timestamp' was not recognized as a valid DateTime. How can I fix this problem?

public void Kafka_consumer()
{
   //some code for getting message from Kafka topic
   Kafka_TimeStamp_string = consumeResult.Message.Timestamp.ToString();
   TimeStamp_dateTime = DateTime.ParseExact(Kafka_TimeStamp_string, "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
}
1

There are 1 best solutions below

0
Guru Stron On BEST ANSWER

You can just use Confluent.Kafka.Timestamp.UtcDateTime:

DateTime dt = consumeResult.Message.Timestamp.UtcDateTime;

There is no reason to convert it to string even if the type had ToString overloaded (currently it does not so you get the default one which returns the type name).