如何使用 C#.net 将 HH:MM:SS 转换为几秒钟?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/682039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do i convert HH:MM:SS into just seconds using C#.net?
提问by Andrew
Is there a tidy way of doing this rather than doing a split on the colon's and multipling out each section the relevant number to calculate the seconds?
有没有一种整洁的方法来做到这一点,而不是在冒号上进行拆分并将每个部分乘以相关数字来计算秒数?
采纳答案by Michael Piendl
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;
回答by Alan
TimeSpan.Parse() will parse a formatted string.
TimeSpan.Parse() 将解析格式化的字符串。
So
所以
TimeSpan.Parse("03:33:12").TotalSeconds;
回答by Jesper Fyhr Knudsen
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'. TotalSeconds return 10 * 3600 + 20 * 60 + 30
秒返回“30”。TotalSeconds 返回 10 * 3600 + 20 * 60 + 30
回答by James Lawruk
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
"30" -> 24 秒
"1:30" -> 90 秒
"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;
回答by Gokul
//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;