2010-01-12 12 views

Odpowiedz

5

Jeśli otrzymasz ciąg formatu "33 hr 40 mins 40 secs", musisz najpierw przeanalizować ciąg znaków.

var s = "33 hr 40 mins 40 secs"; 
var matches = Regex.Matches(s, "\d+"); 
var hr = Convert.ToInt32(matches[0]); 
var min = Convert.ToInt32(matches[1]); 
var sec = Convert.ToInt32(matches[2]); 
var totalSec = hr * 3600 + min * 60 + sec; 

Ten kod oczywiście nie zawiera sprawdzania błędów. Więc warto robić takie rzeczy jak upewnić się, że zostały znalezione 3 mecze, że mecze są ważne wartości minutach i sekundach, itp

14
new TimeSpan(33, 40, 40).TotalSeconds; 
2

oddzielny godziny, minuty i sekundy i następnie wykorzystać

Edited

TimeSpan ts = new TimeSpan(33,40,40); 

/* Gets the value of the current TimeSpan structure expressed in whole 
    and fractional seconds. */ 
double totalSeconds = ts.TotalSeconds; 

Re ad TimeSpan.TotalSeconds Property

+0

to nie będzie działać. 'TimeSpan.Parse' obsługuje tylko godziny do 23 i generuje wyjątek OverflowException –

0

Spróbuj tego -

// Calculate seconds in string of format "xx hr yy mins zz secs" 
    public double TotalSecs(string myTime) 
    { 
     // Split the string into an array 
     string[] myTimeArr = myTime.Split(' '); 

     // Calc and return the total seconds 
     return new TimeSpan(Convert.ToInt32(myTimeArr[0]), 
          Convert.ToInt32(myTimeArr[2]), 
          Convert.ToInt32(myTimeArr[4])).TotalSeconds; 

    } 
Powiązane problemy