[英]Convert MM:SS to Seconds
Is it possible to convert a time such as audio duration into seconds? 是否可以将音频持续时间等时间转换为秒? The format the duration is in is a digital format:
6:30
which represents 6 minutes 30 seconds. 持续时间的格式为数字格式:
6:30
: 6:30
,表示6分30秒。
I've tried 我试过了
TimeSpan.Parse(duration).TotalSeconds
Where duration is 6:30
but it gives an overflow exception. 持续时间为
6:30
但会产生溢出异常。
Should TimeSpan.Parse
be able to parse such strings? TimeSpan.Parse
应该能够解析这样的字符串吗?
Edit: 编辑:
To update from a question asked in the comments the format is not always MM:SS
. 要从注释中提出的问题更新,格式不一定总是
MM:SS
。 If the audio file is over an hour in duration it could also be HH:MM:SS
. 如果音频文件持续时间超过一个小时,则也可能是
HH:MM:SS
。
You can use TimeSpan.ParseExact
, you need to escape the colon: 您可以使用
TimeSpan.ParseExact
,您需要转义冒号:
TimeSpan duration = TimeSpan.ParseExact("6:30", "h\\:mm", CultureInfo.InvariantCulture);
int seconds = (int)duration.TotalSeconds; // 23400
Edit : But you should also be able to use TimeSpan.Parse
: 编辑 :但是您也应该可以使用
TimeSpan.Parse
:
duration = TimeSpan.Parse("6:30", CultureInfo.InvariantCulture);
Note that the maximum is 24 hours. 请注意,最长为24小时。 If it's longer you need to use
DateTime.ParseExact
. 如果更长,则需要使用
DateTime.ParseExact
。
But even this long time is working without an overflow (as you've mentioned). 但是,即使是很长时间也没有溢出(正如您所提到的)。
string longTime = "23:33:44";
TimeSpan duration = TimeSpan.Parse(longTime, CultureInfo.InvariantCulture);
int seconds = (int)duration.TotalSeconds; // 84824
You can even pass multiple allowed formats to TimeSpan.ParseExact
: 您甚至可以将多种允许的格式传递给
TimeSpan.ParseExact
:
string[] timeformats = { @"m\:ss", @"mm\:ss", @"h\:mm\:ss" };
duration = TimeSpan.ParseExact("6:30", timeformats, CultureInfo.InvariantCulture);
A simple string manipulation is an alternative way to do it, posted purely for reference. 简单的字符串操作是一种替代方法,仅供参考。 I'd recommend the
TimeSpan.ParseExact()
method instead. 我建议改为使用
TimeSpan.ParseExact()
方法。
string[] splitDuration = duration.Split(':');
int minutes = Convert.ToInt32(splitDuration[0]);
int seconds = minutes * 60 + Convert.ToInt32(splitDuration[1]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.