0

I am currently tryibng to convert a given time(Entered via a text box) , The time entered would look a little like 01 52 22 mins secs mili secs.

however Timespan.parse(tbName.text) gives me an incorrect format error.

I have got it to work if i input something like 46 in to the textbox but then it sets the days to 46 not the seconds.

Any ideas how to get it just to set the mins seconds and mili seconds from the text input stated above?

I am pretty sure timespan is the way to go but many posts i have read use the dateTime and only use the time part of the variable via formatting

4

2 回答 2

1

Wonderful docs on MDSN, did you bother looking there first?

http://msdn.microsoft.com/en-us/library/se73z7b9.aspx

于 2010-02-07T16:19:25.220 回答
1

要解析的字符串的规范是

[ws][-]{ d | [d.]hh:mm[:ss[.ff]] }[ws]

wherews是空格,d是从 0 到 10675199 的天数,其余的含义很明显(如果您不知道如何阅读这样的规范,方括号中的项目是可选的,必须从 curly 内的项目中选择一项大括号1 ). 因此,如果您想解析"01 52 22"TimeSpanwith TimeSpan.Minutes == 1TimeSpan.Seconds == 52那么TimeSpan.Milliseconds == 22您要么需要将输入重新格式化为"00:01:52.22"并解析

字符串 s = "00:01:52.22"; TimeSpan t = TimeSpan.Parse(s);

或者像这样自己解析字符串

string s = "01 52 22";
string[] fields = s.Split(' ');
int minutes = Int32.Parse(fields[0]);
int seconds = Int32.Parse(fields[1]);
int milliseconds = Int32.Parse(fields[2]);
TimeSpan t = new TimeSpan(0, 0, minutes, seconds, millseconds);

如果我在文本框中输入 46 之类的内容,我就可以让它工作,但它会将天数设置为 46 而不是秒数。

因此,参考上面的规范,"46"解析为TimeSpanwith的原因TimeSpan.Days == 46是因为再次查看规范

[ws][-]{ d | [d.]hh:mm[:ss[.ff]] }[ws]

没有空格,没有-,没有尾随空格,我们减少看

d

或者

[d.]hh:mm[:ss[.ff]]

并且"46"显然符合以前的规范,因此可以如您所见那样进行解析。

1:帮自己一个忙,学习正则表达式;虽然以上不是正则表达式,但理解它们将帮助您阅读上述规范。我推荐掌握正则表达式。理解形式语法也有帮助。

于 2010-02-07T16:37:01.497 回答