2010-01-12 105 views

回答

5

如果給出格式爲"33 hr 40 mins 40 secs"的字符串,則必須先解析字符串。

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; 

該代碼顯然沒有涉及錯誤檢查。所以,你可能想要做這樣的事情,確保3場比賽中發現,該場比賽是分秒的有效值等

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

獨立小時,分鐘和秒,然後使用特定的格式

編輯

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; 

回覆ad TimeSpan.TotalSeconds Property

+0

這是不行的。 'TimeSpan.Parse'只能處理23個小時,並且會爲此拋出一個OverflowException異常 – 2010-01-12 10:14:47

0

試試這個 -

// 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; 

    }