I have to parse time given in hours, minutes, seconds and fraction of seconds. Such as
"15:42:58.1"
"15:42:58.21"
"15:42:58.417"
using the following code:
DateTime.ParseExact("15:42:58.1", "HH:mm:ss.0.f", CultureInfo.InvariantCulture);
This works with excactly one decimal. Any other nomber of decimal will cause an exception.
Question:
You can use TimeSpan
if this is a time of day or similar. See Custom TimeSpan format strings. The trick from Jeroen Mostert's comment to your question still applies: Use capital F
s.
You must escape the delimiters with TimeSpan
format strings. Therefore, use one of:
var ts1 = TimeSpan.ParseExact("15:42:58.1", @"hh\:mm\:ss\.FFFFFFF", CultureInfo.InvariantCulture);
var ts2 = TimeSpan.ParseExact("15:42:58.1", "hh':'mm':'ss'.'FFFFFFF", CultureInfo.InvariantCulture);
This appears to work even with trailing zeros, e.g. "15:42:58.10"
parses OK.
EDIT: Since 2021 (.NET 6), you can also pick the TimeOnly
struct. It represent a time-of-day without any date (whereas TimeSpan
represents a positive or negative amount of time that could span several days, yes, even thousands of days).
You can use array of DateTimeFormat. like
string[] validFormats = { "HH:mm:ss.f", "HH:mm:ss.ff", "HH:mm:ss.fff" };
DateTime.ParseExact("15:42:58.1", validFormats, CultureInfo.InvariantCulture, DateTimeStyles.None);
Now this will parse your DateTime
, even if you fraction of 3 digits
.net Fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With