我怎样才能的String.Format在.NET中使用自定义格式的TimeSpan对象? [英] How can I String.Format a TimeSpan object with a custom format in .NET?

查看:319
本文介绍了我怎样才能的String.Format在.NET中使用自定义格式的TimeSpan对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是格式化时间跨度的推荐对象的方式转换成字符串格式自定义?

What is the recommended way of formatting TimeSpan objects into a string with a custom format?

推荐答案

请注意:这个答案是对.NET 4.0及以上。如果你想在.NET 3.5中格式化时间跨度或以下,请参阅 JohannesH的回答

Please note: this answer is for .Net 4.0 and above. If you want to format a TimeSpan in .Net 3.5 or below please see JohannesH's answer.

自定义时间跨度格式字符串在.NET 4.0中引入的。你可以找到可用的格式说明在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

您需要躲避:字有\(其本身必须除非您使用的是逐字的字符串进行转义)

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:

自定义时间跨度格式说明不包括占位符分隔符号,如符号,从小时分开的日子,时间从几分钟,或分数秒秒。相反,这些符号必须包括在自定义格式字符串作为字符串文字。例如,DD.HH \:毫米限定期间天小时之间的隔板,和一个冒号(:)作为小时和分钟之间的分隔

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.

这篇关于我怎样才能的String.Format在.NET中使用自定义格式的TimeSpan对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆