问题描述
将 TimeSpan
对象格式化为具有自定义格式的字符串的推荐方法是什么?
What is the recommended way of formatting TimeSpan
objects into a string with a custom format?
推荐答案
请注意:此答案适用于 .Net 4.0 及更高版本.如果您想在 .Net 3.5 或更低版本中格式化 TimeSpan,请参阅 JohannesH 的回答.
.Net 4.0 中引入了自定义 TimeSpan 格式字符串.您可以在 MSDN 自定义时间跨度格式字符串一个>页面.
Custom TimeSpan format strings were introduced in .Net 4.0. You can find a full reference of available format specifiers at the MSDN Custom TimeSpan Format Strings page.
这是一个示例时间跨度格式字符串:
Here's an example timespan format string:
string.Format("{0:hh\:mm\:ss}", myTimeSpan); //example output 15:36:15
(UPDATE) 这是一个使用 C# 6 字符串插值的示例:
(UPDATE) and here is an example using C# 6 string interpolation:
$"{myTimeSpan:hh\:mm\:ss}"; //example output 15:36:15
您需要使用"转义:"字符(除非您使用逐字字符串,否则必须对其本身进行转义).
You need to escape the ":" character with a "" (which itself must be escaped unless you're using a verbatim string).
MSDN 自定义时间跨度格式字符串页面的这段摘录解释了关于转义:"和."格式字符串中的字符:
This excerpt from the MSDN Custom TimeSpan Format Strings page explains about escaping the ":" and "." characters in a format string:
自定义 TimeSpan 格式说明符不包含占位符分隔符,例如将天与小时、小时与分钟或秒与小数秒分开的符号.相反,这些符号必须作为字符串文字包含在自定义格式字符串中.例如,dd.hh:mm"将句点 (.) 定义为天和小时之间的分隔符,将冒号 (:) 定义为小时和分钟之间的分隔符.
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.
这篇关于如何在 .NET 中使用自定义格式对 TimeSpan 对象进行 String.Format ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!