2
我想知道如何將時間分成兩個變量。拆分C#中的兩個變量的時間
我得到我的時間這樣
string myTime = Console.ReadLine();
,如果我在12:14我該怎麼做才能得到另一個在一個變量12和14型?
我想知道如何將時間分成兩個變量。拆分C#中的兩個變量的時間
我得到我的時間這樣
string myTime = Console.ReadLine();
,如果我在12:14我該怎麼做才能得到另一個在一個變量12和14型?
其解析爲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
}
通過使用String.Split()
方法。
string [] result = myTime.Split(':');
string hours = result[ 0 ];
string minutes = result[ 1 ];
比我的建議更好的解決方案 – 2010-12-02 10:17:38