2010-01-12 14 views

Respuesta

5

Si le dan una cadena del formato "33 hr 40 mins 40 secs", primero tendrá que analizar la cadena.

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; 

Ese código, obviamente, no tiene ninguna comprobación de error implicada. Así que es posible que desee hacer cosas como asegurarse de que se encontraron 3 partidos, que los partidos son valores válidos para los minutos y segundos, etc.

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

de horas independiente, minutos y segundos y luego usar

Editado

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 anuncio TimeSpan.TotalSeconds Property

+0

esto no funcionará. 'TimeSpan.Parse' solo maneja horas hasta 23, y arrojará una OverflowException para esto –

0

Prueba esto -

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

    } 
Cuestiones relacionadas