简体   繁体   English

如何使用 C#.net 将 HH:MM:SS 转换为几秒钟?

[英]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.您可以在 aTimeSpan 上使用 parse 方法。

http://msdn.microsoft.com/en-us/library/system.timespan.parse.aspx 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如果您只想要秒数,则 TotalSeconds 属性返回总秒数,然后使用 seconds 属性

int seconds = ts.Seconds;

Seconds return '30'.秒返回“30”。 TotalSeconds return 10 * 3600 + 20 * 60 + 30 TotalSeconds 返回 10 * 3600 + 20 * 60 + 30

TimeSpan.Parse() will parse a formatted string. TimeSpan.Parse() 将解析格式化的字符串。

So所以

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

This code allows the hours and minutes components to be optional.此代码允许小时和分钟组件是可选的。 For example,例如,

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

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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