Parse string to TimeSpan
Asked Answered
M

5

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?

Meshach answered 25/8, 2008 at 20:16 Comment(0)
L
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());
Leslee answered 25/8, 2008 at 20:20 Comment(4)
I would suggest using perhaps TimeSpan.TryParse("hh'h:'mm'm'", out span) for a cleaner and more robust solutionPartite
Except when the string is 25h:30mCaracalla
@fubo any solution not limited ?Sot
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 #24369559Sot
T
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.

Teller answered 25/8, 2008 at 20:23 Comment(1)
TimeSpan.TryParseExact was added in .NET 4.0.Alysiaalyson
R
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.

Ratable answered 25/8, 2008 at 20:22 Comment(0)
G
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();
Gascon answered 25/8, 2008 at 20:24 Comment(1)
What's about TimeSpan.TryParse("hh'h:'mm'm'", out span) ? https://mcmap.net/q/275906/-parse-string-to-timespanSot
S
2

From another thread:

How to convert xs:duration to timespan

Stillness answered 4/6, 2009 at 20:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.