1

我想将时间设置为几分钟到几秒钟,有人知道这段代码有什么问题吗?(时间mm:ss,hhss,hh。例如01:12,1072,10秒)

public double timeToSeconds(string TimeToSplit)
{
    string[] Timesplitter = new string[2];
    double minutes;
    double seconds;
    Timesplitter = TimeToSplit.Split(':');

    minutes = double.Parse(Timesplitter[0]);        //double with minutes
    seconds = double.Parse(Timesplitter[1]);        //double with seconds
    if (minutes != 0)
    {
        seconds = seconds + (minutes * 60);
    }
    return seconds;
}
4

4 回答 4

7

您应该使用TimeSpan. 这是解析它的一种方法:

TimeSpan ts = TimeSpan.ParseExact("01:12,10", "mm\\:ss\\,ff", null);
double seconds = ts.TotalSeconds;
return seconds; // it's 72.1
于 2013-05-17T12:15:00.150 回答
1

您最好使用 DateTime 对象而不是双打并使用 TimeSpan 的 TotalSeconds

于 2013-05-17T12:11:15.933 回答
0

您应该将字符串解析为 TimeSpan:

CultureInfo provider = CultureInfo.InvariantCulture;
TimeSpan ts = TimeSpan.ParseExact(TimeToSplit, "mm\\:ss\\,ff", provider);

return ts.TotalSeconds
于 2013-05-17T12:16:06.697 回答
0

问题是您使用逗号作为数字的小数分隔符。您的代码在具有使用逗号的语言环境的系统上运行良好(例如德语);但是,所有其他人都会中断,因为逗号是那里的千位分隔符。

You can specify the locale when running double.Parse. A possible solution would be to replace the comma by a dot and use an invariant locale:

double.Parse(Timesplitter[1].Replace(',', '.'), CultureInfo.InvariantCulture)

This will allow you to use both dots or commas.

That being said, using TimeSpan as others suggested is definitely the better option.

于 2013-05-17T12:19:22.333 回答