Home:ALL Converter>C# parse DateTime String to time only

C# parse DateTime String to time only

Ask Time:2021-06-14T15:01:56         Author:Donkanaille

Json Formatter

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.

Author:Donkanaille,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/67966031/c-sharp-parse-datetime-string-to-time-only
Tim Schmelter :

Your code is almost working, but ParseExact needs two additional arguments and ToString needs upper-case HH for 24h format:\nvar Time1 = DateTime.ParseExact("2021-06-14 19:27:14:979", "yyyy-MM-dd HH:mm:ss:fff", null, DateTimeStyles.None);\nvar Time2 = Time1.ToString("HH:mm:ss:fff");\n\nRead: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings#uppercase-hour-h-format-specifier\nInstead of passing null as format provider(means current culture) you might want to pass a specifc CultureInfo, for example CultureInfo.CreateSpecificCulture("en-US").",