您必须为ICustomFormatter 创建一个实现。当您转换为字符串时,您必须提供该实现。需要注意的是,简单地调用 ToString overload on the TimeSpan that accepts an IFormatProvider 是行不通的,因为它总是需要一个 DateTimeFormatInfo 实例。
这是一个 CustomFormatter,可以满足您的需求:
class TotalMinutesFormatter:ICustomFormatter, IFormatProvider
{
// IFormatProvider.GetFormat
public object GetFormat(Type formatType)
{
//return ourself
if (formatType == typeof(ICustomFormatter))
return this;
else
return null;
}
// ICustomFormatter.Format fmt will have ww:ss and value will be the TimeSpan
public string Format(string fmt, object value, IFormatProvider fp)
{
if (value is TimeSpan) {
var ts = (TimeSpan) value;
var sb = new StringBuilder();
switch(fmt)
{
case "ww:ss":
// calc minutes
var minutes = ts.Hours*60+ts.Minutes;
sb.AppendFormat("{0:00}:{1:00}", minutes, ts.Seconds);
break;
default:
// non recognized format
sb.AppendFormat(fmt,value);
break;
}
return sb.ToString(); // the TimeSpan as string
}
// default fallback
return String.Format(fmt,value);
}
}
以下是您需要如何使用格式化程序:
var myTimeSpan = new TimeSpan(1, 20, 10);
Console.WriteLine(String.Format(new TotalMinutesFormatter(), "{0:ww:ss}", myTimeSpan));
同样,myTimeSpan.ToString("ww:ss", new TotalMinutesFormatter()) 将不起作用并导致 FormatException:
输入的字符串格式不正确
如果您提供了一个 CustomFormatter,TimeSpan.ToString 的内部实现不支持。