TimeSpan.ToString("hh:mm") 错误

TimeSpan.ToString("hh:mm") error

为什么我想获取自定义格式的 TimeSpan 的字符串时出错。

DateTime.Now.TimeOfDay.ToString("hh:mm");
// Error: Input string was not in a correct format.

不要使用TimeOfDay。直接在 DateTime.Now:

上做 ToString()
DateTime.Now.ToString("hh:mm");

TimeOfDay 是一个 TimeSpan。文档清楚地说明了 TimeSpan.ToString(string format) 过载:

格式参数可以是 TimeSpan 值的任何有效标准或自定义格式说明符。如果 format 等于 String.Empty 或为 null,则当前 TimeSpan 对象的 return 值使用通用格式说明符 ("c") 进行格式化。如果 format 是任何其他值,该方法将抛出 FormatException。

如果您必须使用 TimeSpan 变量来执行此操作,您只需将其添加到时间部分设置为零的 DateTime 变量,然后使用其 ToString() :

DateTime.Today.Add(YourTimeSpanVariable).ToString("hh:mm");

根据 MSDN TimeOfDay 是一个 TimeSpan。在 TimeSpan.ToString 的示例中,您会看到 : 需要转义。

hh\:mm\:ss: 03:00:00

这在微软的页面上也有解释Custom TimeSpan Format Strings

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.

所以尝试:

DateTime.Now.TimeOfDay.ToString("hh\:mm");      
DateTime.Now.TimeOfDay.ToString(@"hh\:mm\:ss")

Documentation