How can I String.Format a TimeSpan object with a custom format in .NET?(如何在 .NET 中使用自定义格式对 TimeSpan 对象进行 String.Format ?)
问题描述
将 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 ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 .NET 中使用自定义格式对 TimeSpan 对象进行 String.Format ?
基础教程推荐
- 全局 ASAX - 获取服务器名称 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
