c# - 如何在 .NET 中使用自定义格式对 TimeSpan 对象进行 String.Forma

TimeSpan 对象格式化为具有自定义格式的字符串的推荐方法是什么?

最佳答案

请注意:此答案适用于 .Net 4.0 及更高版本。如果您想在 .Net 3.5 或更低版本中格式化 TimeSpan,请参阅 JohannesH's answer .

.Net 4.0 中引入了自定义 TimeSpan 格式字符串。您可以在 MSDN Custom TimeSpan Format Strings 上找到可用格式说明符的完整引用。页面。

这是一个示例时间跨度格式字符串:

string.Format("{0:hh\\:mm\\:ss}", myTimeSpan); //example output 15:36:15

(UPDATE) 这是一个使用 C# 6 字符串插值的示例:

$"{myTimeSpan:hh\\:mm\\:ss}"; //example output 15:36:15

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

这段摘自 MSDN 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.

关于c# - 如何在 .NET 中使用自定义格式对 TimeSpan 对象进行 String.Format ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/574881/

相关文章:

python - 如何自定义 Python 日志记录的时间格式?

java - 如何格式化带有前导零的Java字符串?

jquery - 使用 jQuery 将文本插入 textarea

c# - 自定义数字格式字符串以始终显示符号

python - 格式化没有尾随零的 float

c# - 格式化 XML 字符串以打印友好的 XML 字符串

c# - 如何在 C# 中将字符串格式化为电话号码

python - 如何在 Python 中打破这条长线?

java - 如何在 Java 中打印带有 2 位小数的 float ?

windows - 在 Windows 批处理脚本中格式化日期和时间