简体   繁体   English

如何格式化这个 TimeSpan 类型的字符串

[英]How to format this string of type TimeSpan

I have a string with this format:我有一个这种格式的字符串:

"09:00"

i want convert this string for this format:我想将此字符串转换为这种格式:

 "9h"

what is the simplest way to format this string?格式化此字符串的最简单方法是什么?

As per the documentation page entitled Custom TimeSpan format strings :根据标题为自定义时间跨度格式字符串的文档页面:

  • We can parse a string to a TimeSpan using TimeSpan.Parse(value)我们可以使用TimeSpan.Parse(value)string解析为TimeSpan
  • We can use %h to get the hour component.我们可以使用%h来获取小时分量。
  • We can use 'h' to add the literal text "h".我们可以使用'h'来添加文字文本“h”。

Putting that together:把它放在一起:

string formatted = TimeSpan.Parse("09:00").ToString("%h'h'"); // 9h

Note that TimeSpan.Parse("09:00") will only work if your culture is able to parse the timespan in this format.请注意, TimeSpan.Parse("09:00")仅在您的文化能够以这种格式解析时间跨度时才有效。 It might be safer to pass in a culture value to an appropriate overload of TimeSpan.Parse .将文化值传递给TimeSpan.Parse适当重载可能更安全。 For example:例如:

TimeSpan.Parse("09:00", System.Globalization.CultureInfo.InvariantCulture);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM