Calculation of Total seconds from a particular format of time
How to calculate total seconds of '33 hr 40 mins 40 secs'开发者_Go百科 in asp.net c#
new TimeSpan(33, 40, 40).TotalSeconds;
If you're given a string of the format "33 hr 40 mins 40 secs"
, you'll have to parse the string first.
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;
That code, obviously, has no error checking involved. So you might want to do things like make sure that 3 matches were found, that the matches are valid values for minutes and seconds, etc.
Separate hour, minute and seconds and then use
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;
Read TimeSpan.TotalSeconds Property
Try this -
// 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;
}
精彩评论