开发者

Split time to two variables in C#

开发者 https://www.devze.com 2023-01-28 17:26 出处:网络
I wonder how i can split a time in to two variables. I get my time like this str开发者_开发知识库ing myTime = Console.ReadLine();

I wonder how i can split a time in to two variables.

I get my time like this

str开发者_开发知识库ing myTime = Console.ReadLine();

and if i type in 12:14 how can i do to get 12 in one variable and 14 in another?


Parse it to a TimeSpan and pull out the parts that way:

TimeSpan ts = TimeSpan.Parse("12:14");
int hours = ts.Hours;
int minutes = ts.Minutes;

One extra upside with using TimeSpan is that it also validates for you. Especially when paired with the TryParse method, this can produce highly reliable code:

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
}


By using the String.Split() method.

string [] result = myTime.Split( ':' );
string hours = result[ 0 ];
string minutes = result[ 1 ];
0

精彩评论

暂无评论...
验证码 换一张
取 消