要从 a 转换为TimeSpan
astring
您可以利用TimeSpan.Parse
,但您必须符合以下格式[ws][-]{ d | [d.]hh:mm[:ss[.ff]] }[ws]
:
ws is Optional white space.
- is An optional minus sign, which indicates a negative TimeSpan.
d is Days, ranging from 0 to 10675199.
. is A culture-sensitive symbol that separates days from hours. The invariant format uses a period (".") character.
hh is Hours, ranging from 0 to 23.
: is The culture-sensitive time separator symbol. The invariant format uses a colon (":") character.
mm is Minutes, ranging from 0 to 59.
ss is Optional seconds, ranging from 0 to 59.
. is A culture-sensitive symbol that separates seconds from fractions of a second. The invariant format uses a period (".") character.
ff is Optional fractional seconds, consisting of one to seven decimal digits.
因此,只需转换天数,您实际上就可以使用TimeSpan.Parse
并传入字符串 - 但如果您想转换分钟数,则需要对输入进行一些按摩,如下所示:
var input = string.Format("00:{0}", objTextBox.Text.PadLeft(2, '0'));
所以你可以发出var timeSpan = TimeSpan.Parse(input);
,因为你已经正确格式化它并且Parse
会成功。我猜另一种选择是将分钟变成几天,但这需要一些浮点工作,而且实际上,IMO 并不是一个好的选择。