TimeSpan addition and subtraction
I need to add 2 times taken from a textbox formatted like this: mm: ss.fff
For example: 00:59,800
+ 00:02,300
- the result should be 01:02.100
, but instead I have 01:02,060
.
I think I have a problem with my transformation below:
string Sum1 = "00:" + "00:59,800";
Sum1 = Sum1.Replace(',', '.');
double FSum1 = TimeSpan.Parse(Sum1).TotalSeconds;
string Sum2 = "00:" + "00:02,300";
Sum2 = Sum2.Replace(',', '.');
double FSum2 = TimeSpan.Parse(Sum2).TotalSeconds;
double SumResult = FSum1 + FSum2;
maskedTextBoxSumResult.Text = TimeSpan.FromMinutes(SumResult).ToString(@"hh\:mm\:ss\.fff");
Also, I need to do the same with subtraction.
Thank you for your help.
+3
source to share
5 answers
Are you looking for TimeSpan.ParseExact
?
string left = "00:59,800";
string right = "00:02,300";
var result = TimeSpan.ParseExact(left, @"mm\:ss\,fff", CultureInfo.InvariantCulture) +
TimeSpan.ParseExact(right, @"mm\:ss\,fff", CultureInfo.InvariantCulture);
Console.Write(result.ToString(@"mm\:ss\.fff"));
Result:
01:02.100
+9
source to share
Do not modify the string to parse it. Use correct cultural information instead:
string Sum1 = "00:" + "00:59,800";
string Sum2 = "00:" + "00:02,300";
var frfr = new System.Globalization.CultureInfo("fr-FR");
var FSum1 = TimeSpan.Parse(Sum1, frfr);
var FSum2 = TimeSpan.Parse(Sum2, frfr);;
var SumResult = FSum1 + FSum2;
SumResult.ToString(@"hh\:mm\:ss\.fff").Dump();
0
source to share
Many of your transformations are unnecessary. Try the following:
static void Main()
{
string Sum1 = "00:" + "00:59,800";
Sum1 = Sum1.Replace(',', '.');
var FSum1 = TimeSpan.Parse(Sum1);
string Sum2 = "00:" + "00:02,300";
Sum2 = Sum2.Replace(',', '.');
var FSum2 = TimeSpan.Parse(Sum2);
var SumResult = FSum1 + FSum2;
var bo = SumResult.ToString(@"hh\:mm\:ss\.fff");
Console.WriteLine(bo);
Console.ReadLine();
}
-1
source to share