我想知道是否有办法将24小时时间格式的字符串转换为TimeSpan.
现在我有一个"旧时尚风格":
string stringTime = "07:35";
string[] values = stringTime.Split(':');
TimeSpan ts = new TimeSpan(values[0], values[1], 0);
Run Code Online (Sandbox Code Playgroud) 我有一些xxh:yym格式的字符串,其中xx是小时,yy是分钟,如"05h:30m".将此类型的字符串转换为TimeSpan的优雅方法是什么?
我在TimeSpan类中遇到一个小问题,它可以解析23:59而不是24:00.
当然,客户想要在24:00输入以表示当天结束而不是23:59或00:00,因为00:00表示当天的开始.
目前我的代码解析结束时间如下:
if ( !TimeSpan.TryParse( ( gvr.FindControl( "txtTimeOff" ) as TextBox ).Text, out tsTimeOff ) )
{
this.ShowValidationError( String.Format( "Please enter a valid 'Time Off' on row '{0}'.", gvr.RowIndex + 1 ) );
return false;
}
Run Code Online (Sandbox Code Playgroud)
对于这种情况,最好的解决办法是什么?
编辑:(解决方案1)
if ( ( gvr.FindControl( "txtTimeOff" ) as TextBox ).Text == "24:00" )
{
tsTimeOff = new TimeSpan( 24, 0, 0 );
}
else
{
if ( !TimeSpan.TryParse( ( gvr.FindControl( "txtTimeOff" ) as TextBox ).Text, out tsTimeOff ) )
{
this.ShowValidationError(
String.Format( …Run Code Online (Sandbox Code Playgroud) 我不确定这里发生了什么,但它会接受一些时间跨度,但不会接受其他时间跨度.有人能告诉我一种检查这种格式99:59:59的时间跨度的方法.
//50:30:00 is bad
//50:20:00 is good
try
{
TimeSpan ts = new TimeSpan();
ts = TimeSpan.Parse("50:30:00");
}
catch //(Exception ex)
{
MessageBox.Show("bad time span");
}
Run Code Online (Sandbox Code Playgroud)