我想知道如何将时间分成两个变量。
我得到这样的时间
string myTime = Console.ReadLine();
如果我输入12:14我怎么能在一个变量中获得12而在另一个变量中获得14?
答案 0 :(得分:9)
将其解析为TimeSpan
并以相应的方式拉出部分:
TimeSpan ts = TimeSpan.Parse("12:14");
int hours = ts.Hours;
int minutes = ts.Minutes;
使用TimeSpan
的一个额外好处是它也会为您验证。特别是当与TryParse
方法配对时,这可以生成高度可靠的代码:
TimeSpan ts;
if (TimeSpan.TryParse("12:99", out ts))
{
// the string is a valid time, use it
}
else
{
// the string is not a valid time, handle that scenario
}
答案 1 :(得分:0)
使用String.Split()
方法。
string [] result = myTime.Split( ':' );
string hours = result[ 0 ];
string minutes = result[ 1 ];