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 ) )
{
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With