我在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( "Please enter a valid 'Time Off' on row '{0}'.", gvr.RowIndex + 1 ) );
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:(解决方案2)
string timeOff = ( gvr.FindControl( "txtTimeOff" ) as TextBox ).Text;
if ( !TimeSpan.TryParse(
timeOff == "24:00" ? "1.00:00:00" : timeOff
, 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)
尝试这样的事情
textBox = (TextBox) gvr.FindControl ("txtTimeOff");
TimeSpan.TryParse (textBox.Text == "24:00"
? "1.00:00"
: textBox.Text,
out tsTimeOff)
Run Code Online (Sandbox Code Playgroud)
此代码可以帮助您:
string span = "35:15";
TimeSpan ts = new TimeSpan(int.Parse(span.Split(':')[0]), // hours
int.Parse(span.Split(':')[1]), // minutes
0); // seconds
Run Code Online (Sandbox Code Playgroud)
from:如何将小时数大于24的字符串解析为TimeSpan?
| 归档时间: |
|
| 查看次数: |
7695 次 |
| 最近记录: |