更改时间跨度毫秒分隔符;逗号 (,) 而不是点 (.)

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

我想输出本地文化中的时间跨度,将其作为 csv 导入 Excel。 时间跨度包含毫秒。

对于英语文化,这意味着例如00:00:01.2345678
对于德国文化,这应该是 00:00:01,2345678(逗号而不是点)

但是无论我为 CultureInfo 对象尝试哪种设置,我都无法让它工作:

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 .)

到目前为止,我什至不知道 CultureInfo class 的哪个属性定义了这个。这是在某处硬编码的吗?

我知道我可以明确定义输出格式:`String.Format("{0:hh\:mm\:ss\,FFFFFFF}", t)

但是有没有办法为此使用 IFormatProvider,以便 c# 将使用给定的 Culture?

使用"g"-format specifier,所以t.ToString("g", culture)。默认情况下,TimeSpan 使用 "c" 格式说明符进行转换,这是一种常见的非文化特定格式。

使用 string.Format 这将是

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

有关格式化时间跨度的更多信息can be found in the docs

这对我有用。 Version fiddle

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

article微软说

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