Work around for TimeSpan parsing 24:00
I have a small issue with the TimeSpan class where it can parse 23:59 but not 24:00.
Of course the client wants to enter 24:00 to indicate the end of the day rather than 23:59 or 00:00 as 00:00 indicates the start of the day.
Currently my code parses the end time like so:
if ( !TimeSpan.TryParse( ( gvr.FindControl( "txtTimeOff" ) as TextBox ).Text, out tsTimeOff 开发者_StackOverflow中文版) )
{
this.ShowValidationError( String.Format( "Please enter a valid 'Time Off' on row '{0}'.", gvr.RowIndex + 1 ) );
return false;
}
Whats the best work around for this situation?
EDIT: (Solution 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;
}
}
EDIT: (solution2)
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;
}
try something like this
textBox = (TextBox) gvr.FindControl ("txtTimeOff");
TimeSpan.TryParse (textBox.Text == "24:00"
? "1.00:00"
: textBox.Text,
out tsTimeOff)
this code may help you:
string span = "35:15";
TimeSpan ts = new TimeSpan(int.Parse(span.Split(':')[0]), // hours
int.Parse(span.Split(':')[1]), // minutes
0); // seconds
from: How to parse string with hours greater than 24 to TimeSpan?
Generally the System.TimeSpan class is not well suited to represent a "point in time" but rather, as the name suggests, a "span" of time or duration. If you can refactor your code to use System.DateTime, or better yet System.DateTimeOffset, that would be the best solution. If that's not possible the other answer from Yahia is your best bet :)
Honestly the best solution is to inform your client that 24:00 is not a valid hour and that he should use 0:00. I've never seen a clock jump from 23:59 to 24:00.
But if you insist ... check out the following SO question which contains the same question and contains a bunch of possible solutions:
Parsing times above 24 hours in C#
精彩评论