Reputation: 1677
I want to set a time in minutes to only seconds, does anyone know what's wrong with this code? (time mm:ss,hh
to ss,hh
. Example 01:12,10
to 72,10
seconds)
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;
}
Upvotes: 1
Views: 377
Reputation: 28747
You should parse your string to a TimeSpan:
CultureInfo provider = CultureInfo.InvariantCulture;
TimeSpan ts = TimeSpan.ParseExact(TimeToSplit, "mm\\:ss\\,ff", provider);
return ts.TotalSeconds
Upvotes: 0
Reputation: 388083
The problem is that you use a comma as the decimal separator of your number. Your code works fine on systems that have a locale that uses a comma for this (for example German); all others will break though, as a comma is a thousands separator there.
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.
Upvotes: 0
Reputation: 56556
You should use a TimeSpan
. Here's one way to parse that:
TimeSpan ts = TimeSpan.ParseExact("01:12,10", "mm\\:ss\\,ff", null);
double seconds = ts.TotalSeconds;
return seconds; // it's 72.1
Upvotes: 7
Reputation: 1129
You are better working with the DateTime object rather than doubles and using TimeSpans's TotalSeconds
Upvotes: 1