String.Format() 时间跨度与日期时间

String.Format() TimeSpan vs DateTime

为什么格式化 TimeSpan 时需要转义分隔符,而格式化 DateTime 时不需要?

示例:

void foo(TimeSpan elapsedTime)
{
    String.Format("Elapsed Time = {0:hh\:mm\:ss\.fff}", elapsedTime);
    String.Format("Now = {0:hh:mm:ss.fff}", DateTime.Now);
}

您需要使用“\”对“:”字符进行转义(除非您使用的是逐字字符串,否则必须对“:”字符进行转义)。

The custom TimeSpan format specifiers do not include placeholder separator symbols, such as the symbols that separate days from hours, hours from minutes, or seconds from fractional seconds. Instead, these symbols must be included in the custom format string as string literals. For example, "dd.hh:mm" defines a period (.) as the separator between days and hours, and a colon (:) as the separator between hours and minutes.

你可以阅读更多here