joeyanthon
joeyanthon

Reputation: 218

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?

Upvotes: 0

Views: 317

Answers (1)

ProgrammingLlama
ProgrammingLlama

Reputation: 38850

As per the documentation page entitled Custom TimeSpan format strings:

  • We can parse a string to a TimeSpan using TimeSpan.Parse(value)
  • We can use %h to get the hour component.
  • We can use 'h' to add the literal text "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. It might be safer to pass in a culture value to an appropriate overload of TimeSpan.Parse. For example:

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

Upvotes: 5

Related Questions