C# 将字符串解析为 TimeSpan
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parse string to TimeSpan
提问by Serhat Ozgel
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?
我有一些 xxh:yym 格式的字符串,其中 xx 是小时,yy 是分钟,如“05h:30m”。将这种类型的字符串转换为 TimeSpan 的优雅方法是什么?
采纳答案by Lars M?hlum
This seems to work, though it is a bit hackish:
这似乎有效,虽然它有点hackish:
TimeSpan span;
if (TimeSpan.TryParse("05h:30m".Replace("m","").Replace("h",""), out span))
MessageBox.Show(span.ToString());
回答by bdukes
Are TimeSpan.Parseand TimeSpan.TryParsenot 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.
是TimeSpan.Parse和TimeSpan.TryParse不选择呢?如果您不使用“已批准”的格式,则需要手动进行解析。我可能会在正则表达式中捕获您的两个整数值,然后尝试将它们解析为整数,从那里您可以使用其构造函数创建一个新的 TimeSpan。
回答by John Sheehan
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
.
DateTime.ParseExact
或者DateTime.TryParseExact
让您指定输入的确切格式。获得后DateTime
,您可以抓取DateTime.TimeOfDay
哪个是一个TimeSpan
。
In the absence of TimeSpan.TryParseExact
, I think an 'elegant' solution is out of the mix.
在没有 的情况下TimeSpan.TryParseExact
,我认为“优雅”的解决方案是不合适的。
@buyutec As you suspected, this method would not work if the time spans have more than 24 hours.
@buyutec 如您所料,如果时间跨度超过 24 小时,则此方法将不起作用。
回答by Vaibhav
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();