Strange TimeSpan.ToString Output

I have a question regarding a character that separates days from hours in TimeSpan.ToString output.

Standard TimeSpan format strings create different delimiter characters:

  • "c" creates a period character (".")
  • "g" and "G" create a colon character (":")

Example:

 // Constant format Console.WriteLine(TimeSpan.FromDays(42).ToString("c", CultureInfo.InvariantCulture)); // Output: 42.00:00:00 (period character between days and hours) // General short format Console.WriteLine(TimeSpan.FromDays(42).ToString("g", CultureInfo.InvariantCulture)); // Output: 42:0:00:00 (colon character between days and hours) // General long format Console.WriteLine(TimeSpan.FromDays(42).ToString("G", CultureInfo.InvariantCulture)); // Output: 42:00:00:00.0000000 (colon character between days and hours) 

Does anyone know that this logic is behind it?

However, TimeSpan.Parse successfully parses all of these lines.

+5
source share
3 answers

These characters are hard-coded for these formats.

For "c" standard format

 [-][d.]hh:mm:ss[.fffffff] 

For "g" standard format

 [-][d:]h:mm:ss[.FFFFFFF] 

And for the "g" Format Specifier

 [-]d:hh:mm:ss.fffffff 

Also doc says:

Unlike the format specifiers "g" and "G", the format specifier "c" is not culturally sensitive. It creates a string representation of the TimeSpan value, which is invariant and is common to all previous versions of the .NET Framework prior to the .NET Framework 4 . "c" is the default TimeSpan format string; formats TimeSpan.ToString () value of the time interval using the format string "c".

Also in Custom TimeSpan format strings

The .NET Framework does not define grammar for time delimited intervals. This means that the separators between days and hours , hours and minutes, minutes and seconds, seconds and fractions of the second should be treated as character literals in the format string.

It seems that the most important reason is the consistency between all versions of the .NET Framework. Perhaps thatโ€™s why they call this format permanent :)

+6
source

More information about MSDN is standard TimeSpan format string .

Essentially:

"c" is a constant format : this specifier is not culturally sensitive. Format [d.] Hh: mm: ss ['. Fffffff]

"g" - General short format : it is culturally sensitive. Format [-] [d:] h: mm: ss [.FFFFFFF]

"G" is the General Long Format : it is culturally sensitive. Format [-] d: hh: mm : ss.fffffff.

+2
source

See MSDN

The "g" format specifier TimeSpan returns a string representation of the TimeSpan value in a compact form, including only the elements that are needed.

[-] [d:] h: mm: ss [.FFFFFFF]

.....................

The format specifier "c" returns a string representation of the TimeSpan value in the following form:

[-] hh [d]: Mm: ss [.fffffff]

0
source

Source: https://habr.com/ru/post/1240694/


All Articles