Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the timespan millisecond separator; comma(,) instead of dot(.) [duplicate]

I want to output a timespan in the local culture, to import it as csv in Excel. The timespan contains milliseconds.

with the english culture, this means e.g. 00:00:01.2345678
with the german culture, this should be 00:00:01,2345678 (comma instead of dot)

But no matter which settings i try for the CultureInfo object, I cannot get it to work:

TimeSpan t = new TimeSpan(12345678);
var cul = CultureInfo.GetCultureInfo("de");
// cul.DateTimeFormat.FullTimeSpanPositivePattern == "d':'h':'mm':'ss','FFFFFFF";
// (note the comma)

Console.WriteLine(String.Format(cul, "{0}", t));
// expected: "00:00:01,2345678" (with ,)
// actual: "00:00:01.2345678" (with .)

So far, I cannot even tell which of the properties of the CultureInfo class defines this. Is this hardcoded somewhere?

I know I can explicitely define the output format: `String.Format("{0:hh\:mm\:ss\,FFFFFFF}", t)

But is there a way to use a IFormatProvider for this, so that c# will use the given Culture?

like image 222
HugoRune Avatar asked Oct 20 '25 17:10

HugoRune


2 Answers

Use the "g"-format specifier, so t.ToString("g", culture). By default a TimeSpan is converted using the "c"-format specifier, which is a common non-culture specific format.

Using string.Format this would be

String.Format(cul, "{0:g}", t)

More info on formatting timespans can be found in the docs

like image 148
ikkentim Avatar answered Oct 22 '25 06:10

ikkentim


This works for me. Version fiddle

TimeSpan t = new TimeSpan(12345678);
var cul = CultureInfo.GetCultureInfo("de");
Console.WriteLine(t.ToString("g", cul));

The article Microsoft said

"g" : This specifier outputs only what is needed. It is culture-sensitive and takes the form [-][d’:’]h’:’mm’:’ss[.FFFFFFF].

like image 38
Antoine V Avatar answered Oct 22 '25 07:10

Antoine V



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!