Donkanaille
Donkanaille

Reputation: 29

C# parse DateTime String to time only

I am new to C# and I have a string like "2021-06-14 19:27:14:979". Now I want to have only the time "19:27:14:979". So do I parse the string to a specific DateTime format and then convert it back to a string or would you parse or cut the string itself?

It is important that I keep the 24h format. I don't want AM or PM.

I haven't found any solution yet. I tried to convert it to DateTime like:

var Time1 = DateTime.ParseExact(time, "yyyy-MM-dd HH:mm:ss:fff"); 
var Time2 = Time1.ToString("hh:mm:ss:fff");

But then I lost the 24h format.

Upvotes: 2

Views: 5884

Answers (2)

Hans Kilian
Hans Kilian

Reputation: 25364

You can just split it at the blank and take the last part like this

var timestamp = "2021-06-14 19:27:14:979";
var timePart = timestamp.Split(' ')[1];

in your case that seems easier than parsing into a DateTime and back into a string.

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460208

Your code is almost working, but ParseExact needs two additional arguments and ToString needs upper-case HH for 24h format:

var Time1 = DateTime.ParseExact("2021-06-14 19:27:14:979", "yyyy-MM-dd HH:mm:ss:fff", null, DateTimeStyles.None);
var Time2 = Time1.ToString("HH:mm:ss:fff");

Read: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings#uppercase-hour-h-format-specifier

Instead of passing null as format provider(means current culture) you might want to pass a specifc CultureInfo, for example CultureInfo.CreateSpecificCulture("en-US").

Upvotes: 4

Related Questions