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?
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
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].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With