Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Work around for TimeSpan parsing 24:00

Tags:

c#

timespan

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;
}
like image 852
WraithNath Avatar asked Sep 15 '11 10:09

WraithNath


3 Answers

try something like this

textBox = (TextBox) gvr.FindControl ("txtTimeOff");

TimeSpan.TryParse (textBox.Text == "24:00"
                      ? "1.00:00"
                      : textBox.Text,
                   out tsTimeOff)
like image 109
Yahia Avatar answered Oct 16 '22 12:10

Yahia


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?

like image 20
Sayed Abolfazl Fatemi Avatar answered Oct 16 '22 11:10

Sayed Abolfazl Fatemi


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 :)

like image 29
MattDavey Avatar answered Oct 16 '22 10:10

MattDavey