简体   繁体   中英

How do i convert HH:MM:SS into just seconds using C#.net?

有没有一种整洁的方法来做到这一点,而不是在冒号上进行拆分并将每个部分乘以相关数字来计算秒数?

It looks like a timespan. So simple parse the text and get the seconds.

string time = "00:01:05";
double seconds = TimeSpan.Parse(time).TotalSeconds;

You can use the parse method on aTimeSpan.

http://msdn.microsoft.com/en-us/library/system.timespan.parse.aspx

TimeSpan ts = TimeSpan.Parse( "10:20:30" );
double totalSeconds = ts.TotalSeconds;

The TotalSeconds property returns the total seconds if you just want the seconds then use the seconds property

int seconds = ts.Seconds;

Seconds return '30'. TotalSeconds return 10 * 3600 + 20 * 60 + 30

TimeSpan.Parse() will parse a formatted string.

So

TimeSpan.Parse("03:33:12").TotalSeconds;

This code allows the hours and minutes components to be optional. For example,

"30" -> 24 seconds
"1:30" -> 90 seconds
"1:1:30" -> 3690 seconds

int[] ssmmhh = {0,0,0};
var hhmmss = time.Split(':');
var reversed = hhmmss.Reverse();
int i = 0;
reversed.ToList().ForEach(x=> ssmmhh[i++] = int.Parse(x));                           
var seconds = (int)(new TimeSpan(ssmmhh[2], ssmmhh[1], ssmmhh[0])).TotalSeconds;  
//Added code to handle invalid strings
string time = null; //"";//"1:31:00";
string rv = "0";
TimeSpan result;
if(TimeSpan.TryParse(time, out result))
{
    rv = result.TotalSeconds.ToString();
}
retrun rv;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM