30

I have some strings of xxh:yym format where xx is hours and yy is minutes like "05h:30m". What is an elegant way to convert a string of this type to TimeSpan?

Serhat Ozgel
  • 23,496
  • 29
  • 102
  • 138

5 Answers5

27

This seems to work, though it is a bit hackish:

TimeSpan span;


if (TimeSpan.TryParse("05h:30m".Replace("m","").Replace("h",""), out span))
            MessageBox.Show(span.ToString());
Lars Mæhlum
  • 6,074
  • 3
  • 28
  • 32
  • 15
    I would suggest using perhaps `TimeSpan.TryParse("hh'h:'mm'm'", out span)` for a cleaner and more robust solution – mike Jan 04 '11 at 23:54
  • 3
    Except when the string is 25h:30m – The_Butcher Sep 14 '11 at 08:39
  • @fubo any solution ***not limited*** ? – Kiquenet Mar 01 '18 at 08:32
  • _If you need to validate that the input string is a valid time-of-day (>= 00:00 and < 24:00), then you should consider this instead_: `DateTime.TryParseExact("07:35", "HH:mm"` view https://stackoverflow.com/questions/24369059/how-to-convert-string-0735-hhmm-to-timespan – Kiquenet Mar 01 '18 at 08:40
7

DateTime.ParseExact or DateTime.TryParseExact lets you specify the exact format of the input. After you get the DateTime, you can grab the DateTime.TimeOfDay which is a TimeSpan.

In the absence of TimeSpan.TryParseExact, I think an 'elegant' solution is out of the mix.

@buyutec As you suspected, this method would not work if the time spans have more than 24 hours.

Echilon
  • 10,064
  • 33
  • 131
  • 217
John Sheehan
  • 77,456
  • 30
  • 160
  • 194
  • [TimeSpan.TryParseExact](http://msdn.microsoft.com/en-us/library/system.timespan.tryparseexact%28v=vs.100%29.aspx) was added in .NET 4.0. – David Dowdle Oct 02 '13 at 14:48
2

Are TimeSpan.Parse and TimeSpan.TryParse not options? If you aren't using an "approved" format, you'll need to do the parsing manually. I'd probably capture your two integer values in a regular expression, and then try to parse them into integers, from there you can create a new TimeSpan with its constructor.

bdukes
  • 152,002
  • 23
  • 148
  • 175
2

Here'e one possibility:

TimeSpan.Parse(s.Remove(2, 1).Remove(5, 1));

And if you want to make it more elegant in your code, use an extension method:

public static TimeSpan ToTimeSpan(this string s)
{
  TimeSpan t = TimeSpan.Parse(s.Remove(2, 1).Remove(5, 1));
  return t;
}

Then you can do

"05h:30m".ToTimeSpan();
Vaibhav
  • 11,310
  • 11
  • 51
  • 70
  • What's about `TimeSpan.TryParse("hh'h:'mm'm'", out span)` ? https://stackoverflow.com/a/26769/206730 – Kiquenet Mar 01 '18 at 08:33
2

From another thread:

How to convert xs:duration to timespan

Community
  • 1
  • 1