Parse string to TimeSpan

六眼飞鱼酱① 提交于 2019-12-03 18:00:33

问题


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?


回答1:


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());



回答2:


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.




回答3:


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();



回答4:


From another thread:

How to convert xs:duration to timespan




回答5:


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.



来源:https://stackoverflow.com/questions/26760/parse-string-to-timespan

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!