TimeSpan timeformat mismatch C#

42 views Asked by At

A line of code where im trying to create a timespan object which contains "00:00:00.000".

My time format is "HH:mm:ss.fff", took it from a code that works with this exact time format in another project I have.

But it gives a mismatch exception.

Chatgpt and other answers in stackoverflow suggested to use CultureInfo from null to the example below, but it does exactly the same exception.

string timeFormat= "HH:mm:ss.fff";
TimeSpan timeZero = TimeSpan.ParseExact("00:00:00.000", timeformat, CultureInfo.InvariantCulture);
1

There are 1 answers

0
Soner Gönül On BEST ANSWER

Timespan parsing is little bit different than DateTime parsing.

From documentation:

Important

The custom TimeSpan format specifiers don't include placeholder separator symbols, such as the symbols that separate days from hours, hours from minutes, or seconds from fractional seconds. Instead, these symbols must be included in the custom format string as string literals. For example, "dd\.hh\:mm" defines a period (.) as the separator between days and hours, and a colon (:) as the separator between hours and minutes.

There is no custom HH specifier for TimeSpan, it should be hh instead. By the way timeFormat and timeformat are different variable names, in C#, these names are case sensitive, you need to fix that as well.

string timeFormat = @"hh\:mm\:ss\.fff";
TimeSpan timeZero = TimeSpan.ParseExact("00:00:00.000", timeFormat, 
                                        CultureInfo.InvariantCulture);

Here a demonstration.

Be aware of that there is a read-only field as TimeSpan.Zero which you can use as well.

As a side note, CultureInfo always matters on parsing or displaying operations. When you use null for CultureInfo, it always uses your CurrentCulture property. That's why your parsing operation might fail if your input string's time separator won't match your current culture's DateTimeFormatInfo.TimeSeparator property.