Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.ParseExact with varible fraction of seconds

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:

  • Is there a generic possibility for the number of decimals of seconds?
like image 568
Yvo Weidmann Avatar asked Sep 12 '25 10:09

Yvo Weidmann


2 Answers

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 Fs.

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).

like image 106
Jeppe Stig Nielsen Avatar answered Sep 14 '25 00:09

Jeppe Stig Nielsen


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

like image 30
Prasad Telkikar Avatar answered Sep 14 '25 01:09

Prasad Telkikar