0

I'm trying to extract string from regular expression and convert it to string and converting it to Timespan again.

static Regex myTimePattern = new Regex(@"((\d+)+(\:\d+))$");

static TimeSpan DurationTimespan(string s)
{
    if (s == null) throw new ArgumentNullException("s");

    Match m = myTimePattern.Match(s);

    if (!m.Success) throw new ArgumentOutOfRangeException("s");

    string hh = m.Groups[0].Value.PadRight(2, '0');
    string mm = m.Groups[2].Value.PadRight(2, '0');

    int hours = int.Parse(hh);
    int minutes = int.Parse(mm);

    if (minutes < 0 || minutes > 59) throw new ArgumentOutOfRangeException("s");

    TimeSpan value = new TimeSpan(hours, minutes, 0);
    return value;
}

string hh shows = "30:00" and mm shows: "30". The time in my textbox from which data is collected is : "01:30:00". Please help me find a way.

Balagurunathan Marimuthu
  • 2,927
  • 4
  • 31
  • 44

3 Answers3

1

If your regular expression would look like this:

   static Regex myTimePattern = new Regex(@"(\d+)+\:(\d+)\:\d+$");

Then you can easily retreive groups as follows:

   string hh = m.Groups[1].Value.PadRight(2, '0');
   string mm = m.Groups[2].Value.PadRight(2, '0');

Do you have a reason why not to use Parse string in HH.mm format to TimeSpan ?

vasek
  • 2,759
  • 1
  • 26
  • 30
0

Your regex covers only mm and ss. You could use this:

static Regex myTimePattern = new Regex(@"(\d{1,2}):(\d{1,2}):(\d{1,2})");
static TimeSpan DurationTimespan( string s )
{
        if ( s == null ) throw new ArgumentNullException("s");
        Match m = myTimePattern.Match(s);
        if ( ! m.Success ) throw new ArgumentOutOfRangeException("s");
        string hh = m.Groups[1].Value;
        string mm = m.Groups[2].Value;

        int hours   = int.Parse( hh );
        int minutes = int.Parse( mm );
        if ( minutes < 0 || minutes > 59 ) throw new ArgumentOutOfRangeException("s");
        TimeSpan value = new TimeSpan(hours , minutes , 0 );
        return value ;
    }
Romano Zumbé
  • 7,893
  • 4
  • 33
  • 55
0
        static Regex myTimePattern = new Regex(@"^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$");
            static TimeSpan DurationTimespan(string s)
            {
                if (s == null) throw new ArgumentNullException("s");
                Match m = myTimePattern.Match(s);
                if (!m.Success)
                    throw new ArgumentOutOfRangeException("s");

                DateTime DT = DateTime.Parse(s);
                TimeSpan value = new TimeSpan(DT.Hour, DT.Minute, 0);

                if (DT.Minute < 0 || DT.Minute > 59)
                    throw new ArgumentOutOfRangeException("s");

                return value;
            }
Von Abanes
  • 706
  • 1
  • 6
  • 19