Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange TimeSpan.ToString output

Tags:

c#

.net

timespan

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

The standard TimeSpan format strings produce different separator symbols:

  • "c" produces a period (".") character
  • "g" and "G" produce 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 anybody know what's the logic behind it?

However TimeSpan.Parse parses all of these string successfully.

like image 746
MaDev Avatar asked Jan 15 '16 13:01

MaDev


2 Answers

These characters are hardcoded for those formats.

For "c" standard format

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

For "g" standard format

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

And for "G" Format Specifier

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

Also doc says;

Unlike the "g" and "G" format specifiers, the "c" format specifier is not culture-sensitive. It produces the string representation of a TimeSpan value that is invariant and that is common to all previous versions of the .NET Framework before the .NET Framework 4. "c" is the default TimeSpan format string; the TimeSpan.ToString() method formats a time interval value by using the "c" format string.

Also in Custom TimeSpan Format Strings

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

Sounds like the most important reason is consistency between all .NET Framework versions. Maybe that's why they call this format as constant :)

like image 83
Soner Gönül Avatar answered Nov 17 '22 16:11

Soner Gönül


There is more detail on MSDN - Standard TimeSpan Format Strings.

Essentially:

"c" is the Constant format: This specifier is not culture-sensitive. Format is [d’.’]hh’:’mm’:’ss[‘.’fffffff]

"g" is the General Short format: This is culture sensitive. Format is [-][d’:’]h’:’mm’:’ss[.FFFFFFF]

"G" is the General Long format: This is culture sensitive. Format is [-]d’:’hh’:’mm’:’ss.fffffff.

like image 2
NikolaiDante Avatar answered Nov 17 '22 17:11

NikolaiDante